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 @@ ...@@ -14,82 +14,19 @@
package org.opengroup.osdu.notification.provider.azure.util; package org.opengroup.osdu.notification.provider.azure.util;
import com.auth0.jwt.JWT; import org.opengroup.osdu.azure.util.AzureServicePrincipleTokenService;
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.core.common.util.IServiceAccountJwtClient; import org.opengroup.osdu.core.common.util.IServiceAccountJwtClient;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; 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 @Component
public class ServiceAccountJwtAzureClientImpl implements IServiceAccountJwtClient { public class ServiceAccountJwtAzureClientImpl implements IServiceAccountJwtClient {
@Autowired @Autowired
private AppProperties config; private AzureServicePrincipleTokenService tokenService;
@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);
if (future == null) { @Override
throw new AppException(HttpStatus.SC_FORBIDDEN, "Token not generated", "The user is not authorized to obtain Token From AAD"); public String getIdToken(String partitionId){
} return "Bearer " + this.tokenService.getAuthorizationToken();
ACCESS_TOKEN = future.get().getAccessToken();
} catch (MalformedURLException malformedURLException) {
malformedURLException.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return ACCESS_TOKEN;
} }
} }
...@@ -14,104 +14,56 @@ ...@@ -14,104 +14,56 @@
package org.opengroup.osdu.notification.util; package org.opengroup.osdu.notification.util;
import org.apache.http.HttpStatus; import org.junit.jupiter.api.Test;
import org.junit.Assert; import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoJUnitRunner; import org.omg.CORBA.portable.ApplicationException;
import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; import org.opengroup.osdu.azure.util.AzureServicePrincipleTokenService;
import org.opengroup.osdu.core.common.model.http.AppException; 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 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.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.times;
import static org.mockito.MockitoAnnotations.initMocks;
@RunWith(MockitoJUnitRunner.class) @ExtendWith(MockitoExtension.class)
public class ServiceAccountClientImplTest { public class ServiceAccountClientImplTest {
final String tenantName = "Test Tenant"; private static final String tenantId = "tenantId";
final String validToken = "validToken"; private static final String token = "jwt-token";
@Mock
private IdToken idToken;
@Mock
private ExecutorService executorService;
@Mock
private AppProperties appProperties;
@Mock
private JwtCache tenantJwtCacheMock;
@Mock
private JaxRsDpsLog logger;
@InjectMocks @InjectMocks
@Spy private ServiceAccountJwtAzureClientImpl serviceAccountJwtAzureClient;
private ServiceAccountJwtAzureClientImpl sut;
@Before @Mock
public void setup() { private AzureServicePrincipleTokenService azureServicePrincipleTokenService;
initMocks(this);
idToken = IdToken.builder().tokenValue(validToken).expirationTimeMillis(System.currentTimeMillis() + 10000000L).build();
}
@Test @Test
public void should_getTokenFromCache_getIdTokenTest() { public void shouldSuccessfullyGenerateToken() throws UnsupportedEncodingException, ApplicationException {
// SetUp
when(tenantJwtCacheMock.get(any())).thenReturn(idToken);
String expectedToken = "Bearer " +idToken.getTokenValue();
// Act when(azureServicePrincipleTokenService.getAuthorizationToken()).thenReturn(token);
String returnedIdToken = sut.getIdToken(tenantName);
// Assert String result = serviceAccountJwtAzureClient.getIdToken(tenantId);
Assert.assertEquals(expectedToken, returnedIdToken);
assertEquals("Bearer " + token, result);
verify(azureServicePrincipleTokenService, times(1)).getAuthorizationToken();
} }
@Test @Test
public void should_updateCache_getIdTokenTest() { public void shouldThrowAppException() throws UnsupportedEncodingException {
// Set up
when(tenantJwtCacheMock.get(any())).thenReturn(idToken);
String expectedToken = "Bearer " +idToken.getTokenValue();
// Act doThrow(AppException.class).when(azureServicePrincipleTokenService).getAuthorizationToken();
String returnedToken = this.sut.getIdToken(tenantName);
// Assert AppException exception = assertThrows(AppException.class, () -> {
Assert.assertEquals(expectedToken, returnedToken); serviceAccountJwtAzureClient.getIdToken(tenantId);
} });
@Test assertNotNull(exception);
public void should_return403GivenInvalidApplicationProperties_getAccessToken() { verify(azureServicePrincipleTokenService, times(1)).getAuthorizationToken();
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());
}
} }
} }
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