Skip to content
Snippets Groups Projects
Commit b0d1d49a authored by Komal Makkar's avatar Komal Makkar
Browse files

Merge branch 'abpatil/token_generation' into 'master'

Using AzureServicePrincipleTokenService in implementation of IServiceAccountJwtClient

See merge request !103
parents 751bf31b 94078b98
No related branches found
No related tags found
1 merge request!103Using AzureServicePrincipleTokenService in implementation of IServiceAccountJwtClient
Pipeline #63065 failed
......@@ -14,82 +14,19 @@
package org.opengroup.osdu.notification.provider.azure.util;
import com.auth0.jwt.JWT;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import org.apache.http.HttpStatus;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.opengroup.osdu.core.common.model.search.IdToken;
import org.opengroup.osdu.core.common.provider.interfaces.IJwtCache;
import org.opengroup.osdu.azure.util.AzureServicePrincipleTokenService;
import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.MalformedURLException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Component
public class ServiceAccountJwtAzureClientImpl implements IServiceAccountJwtClient {
@Autowired
private AppProperties config;
@Autowired
private IJwtCache tenantJwtCache;
public String getIdToken(String tenantName) {
String ACCESS_TOKEN = "";
ExecutorService service = null;
try {
// TODO : Refactor to move ID token form Common.Core.model.search to Common.core
IdToken cachedToken = (IdToken) this.tenantJwtCache.get(tenantName);
if ((cachedToken != null) && !IdToken.refreshToken(cachedToken)) {
return "Bearer " + cachedToken.getTokenValue();
}
// TODO : Control the thread count via config and pool should be created once.
service = Executors.newFixedThreadPool(1);
ACCESS_TOKEN = getAccessToken(service);
IdToken idToken = IdToken.builder().tokenValue(ACCESS_TOKEN).expirationTimeMillis(JWT.decode(ACCESS_TOKEN).getExpiresAt().getTime()).build();
this.tenantJwtCache.put(tenantName, idToken);
} finally {
if(service != null) {
service.shutdown();
}
}
return "Bearer " + ACCESS_TOKEN;
}
// TODO : Refactor for making it test-able.
// THIS METHOD IS PUBLIC ONLY TO ENABLE UNIT TESTING
public String getAccessToken(ExecutorService service) {
AuthenticationContext context = null;
ClientCredential credential = null;
String ACCESS_TOKEN = null;
try {
context = new AuthenticationContext(this.config.getAuthURL(), false, service);
credential = new ClientCredential(this.config.getAuthClientID(), this.config.getAuthClientSecret());
Future<AuthenticationResult> future = context.acquireToken(this.config.getAadClientID(), credential, null);
private AzureServicePrincipleTokenService tokenService;
if (future == null) {
throw new AppException(HttpStatus.SC_FORBIDDEN, "Token not generated", "The user is not authorized to obtain Token From AAD");
}
ACCESS_TOKEN = future.get().getAccessToken();
} catch (MalformedURLException malformedURLException) {
malformedURLException.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return ACCESS_TOKEN;
@Override
public String getIdToken(String partitionId){
return "Bearer " + this.tokenService.getAuthorizationToken();
}
}
......@@ -14,104 +14,56 @@
package org.opengroup.osdu.notification.util;
import org.apache.http.HttpStatus;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog;
import org.mockito.junit.jupiter.MockitoExtension;
import org.omg.CORBA.portable.ApplicationException;
import org.opengroup.osdu.azure.util.AzureServicePrincipleTokenService;
import org.opengroup.osdu.core.common.model.http.AppException;
import org.opengroup.osdu.core.common.model.search.IdToken;
import org.opengroup.osdu.notification.provider.azure.cache.JwtCache;
import org.opengroup.osdu.notification.provider.azure.util.AppProperties;
import org.opengroup.osdu.notification.provider.azure.util.ServiceAccountJwtAzureClientImpl;
import java.util.concurrent.ExecutorService;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.times;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class ServiceAccountClientImplTest {
final String tenantName = "Test Tenant";
final String validToken = "validToken";
@Mock
private IdToken idToken;
@Mock
private ExecutorService executorService;
@Mock
private AppProperties appProperties;
@Mock
private JwtCache tenantJwtCacheMock;
@Mock
private JaxRsDpsLog logger;
private static final String tenantId = "tenantId";
private static final String token = "jwt-token";
@InjectMocks
@Spy
private ServiceAccountJwtAzureClientImpl sut;
private ServiceAccountJwtAzureClientImpl serviceAccountJwtAzureClient;
@Before
public void setup() {
initMocks(this);
idToken = IdToken.builder().tokenValue(validToken).expirationTimeMillis(System.currentTimeMillis() + 10000000L).build();
}
@Mock
private AzureServicePrincipleTokenService azureServicePrincipleTokenService;
@Test
public void should_getTokenFromCache_getIdTokenTest() {
// SetUp
when(tenantJwtCacheMock.get(any())).thenReturn(idToken);
String expectedToken = "Bearer " +idToken.getTokenValue();
public void shouldSuccessfullyGenerateToken() throws UnsupportedEncodingException, ApplicationException {
// Act
String returnedIdToken = sut.getIdToken(tenantName);
when(azureServicePrincipleTokenService.getAuthorizationToken()).thenReturn(token);
// Assert
Assert.assertEquals(expectedToken, returnedIdToken);
String result = serviceAccountJwtAzureClient.getIdToken(tenantId);
assertEquals("Bearer " + token, result);
verify(azureServicePrincipleTokenService, times(1)).getAuthorizationToken();
}
@Test
public void should_updateCache_getIdTokenTest() {
// Set up
when(tenantJwtCacheMock.get(any())).thenReturn(idToken);
String expectedToken = "Bearer " +idToken.getTokenValue();
public void shouldThrowAppException() throws UnsupportedEncodingException {
// Act
String returnedToken = this.sut.getIdToken(tenantName);
doThrow(AppException.class).when(azureServicePrincipleTokenService).getAuthorizationToken();
// Assert
Assert.assertEquals(expectedToken, returnedToken);
}
AppException exception = assertThrows(AppException.class, () -> {
serviceAccountJwtAzureClient.getIdToken(tenantId);
});
@Test
public void should_return403GivenInvalidApplicationProperties_getAccessToken() {
when(appProperties.getAuthURL()).thenReturn("https://login.microsoftonline.com/s/oauth2/token/");
when(appProperties.getAuthClientID()).thenReturn("testAuthClientID");
when(appProperties.getAuthClientSecret()).thenReturn("testAuthClientSecret");
when(appProperties.getAadClientID()).thenReturn("testAadClientID");
try {
// Act
sut.getAccessToken(executorService);
// Assert
fail("Should throw exception");
} catch (AppException appException) {
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, appException.getError().getCode());
} catch (Exception e) {
fail("Should not throw this exception" + e.getMessage());
}
assertNotNull(exception);
verify(azureServicePrincipleTokenService, times(1)).getAuthorizationToken();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment