use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandler method getAccessTokenInfo.
private AccessTokenInfo getAccessTokenInfo(TokenValidationContext validationContext) throws APIManagementException {
Object cachedAccessTokenInfo = CacheProvider.createIntrospectionCache().get(validationContext.getAccessToken());
if (cachedAccessTokenInfo != null) {
log.debug("AccessToken available in introspection Cache.");
return (AccessTokenInfo) cachedAccessTokenInfo;
}
String electedKeyManager = null;
// Obtaining details about the token.
if (StringUtils.isNotEmpty(validationContext.getTenantDomain())) {
Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(validationContext.getTenantDomain());
KeyManager keyManagerInstance = null;
if (tenantKeyManagers.values().size() == 1) {
log.debug("KeyManager count is 1");
Map.Entry<String, KeyManagerDto> entry = tenantKeyManagers.entrySet().iterator().next();
if (entry != null) {
KeyManagerDto keyManagerDto = entry.getValue();
if (keyManagerDto != null && (validationContext.getKeyManagers().contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || validationContext.getKeyManagers().contains(keyManagerDto.getName()))) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDto.getName() + " Available in API level KM list " + String.join(",", validationContext.getKeyManagers()));
}
if (keyManagerDto.getKeyManager() != null && keyManagerDto.getKeyManager().canHandleToken(validationContext.getAccessToken())) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDto.getName() + " can handle the token");
}
keyManagerInstance = keyManagerDto.getKeyManager();
electedKeyManager = entry.getKey();
}
}
}
} else if (tenantKeyManagers.values().size() > 1) {
log.debug("KeyManager count is > 1");
if (validationContext.getKeyManagers().contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS)) {
if (log.isDebugEnabled()) {
log.debug("API level KeyManagers contains " + APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS);
}
for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
if (keyManagerDtoEntry.getValue().getKeyManager() != null && keyManagerDtoEntry.getValue().getKeyManager().canHandleToken(validationContext.getAccessToken())) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDtoEntry.getValue().getName() + " can handle the token");
}
keyManagerInstance = keyManagerDtoEntry.getValue().getKeyManager();
electedKeyManager = keyManagerDtoEntry.getKey();
break;
}
}
} else {
for (String selectedKeyManager : validationContext.getKeyManagers()) {
KeyManagerDto keyManagerDto = tenantKeyManagers.get(selectedKeyManager);
if (keyManagerDto != null && keyManagerDto.getKeyManager() != null && keyManagerDto.getKeyManager().canHandleToken(validationContext.getAccessToken())) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManagerDto.getName() + " can handle the token");
}
keyManagerInstance = keyManagerDto.getKeyManager();
electedKeyManager = selectedKeyManager;
break;
}
}
}
}
if (keyManagerInstance != null) {
log.debug("KeyManager instance available to validate token.");
AccessTokenInfo tokenInfo = keyManagerInstance.getTokenMetaData(validationContext.getAccessToken());
tokenInfo.setKeyManager(electedKeyManager);
CacheProvider.getGatewayIntrospectCache().put(validationContext.getAccessToken(), tokenInfo);
return tokenInfo;
} else {
AccessTokenInfo tokenInfo = new AccessTokenInfo();
tokenInfo.setTokenValid(false);
tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
log.debug("KeyManager not available to authorize token.");
return tokenInfo;
}
}
return null;
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class APIStoreImpl method generateApplicationToken.
@Override
public ApplicationToken generateApplicationToken(String clientId, String clientSecret, String scopes, long validityPeriod, String tokenToBeRevoked) throws APIManagementException {
log.debug("Generating a new application access token");
AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
accessTokenRequest.setClientId(clientId);
accessTokenRequest.setClientSecret(clientSecret);
accessTokenRequest.setGrantType(KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE);
if (StringUtils.isEmpty(scopes)) {
scopes = KeyManagerConstants.OAUTH2_DEFAULT_SCOPE;
}
accessTokenRequest.setScopes(scopes);
accessTokenRequest.setValidityPeriod(validityPeriod);
accessTokenRequest.setTokenToRevoke(tokenToBeRevoked);
AccessTokenInfo newToken = getKeyManager().getNewAccessToken(accessTokenRequest);
ApplicationToken applicationToken = new ApplicationToken();
applicationToken.setAccessToken(newToken.getAccessToken());
applicationToken.setValidityPeriod(newToken.getValidityPeriod());
applicationToken.setScopes(newToken.getScopes());
log.debug("Successfully created a new application access token.");
return applicationToken;
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyManagerImplTestCase method testGetTokenMetaData.
@Test
public void testGetTokenMetaData() throws Exception {
DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
OAuth2ServiceStubs.IntrospectionServiceStub introspectionStub = Mockito.mock(OAuth2ServiceStubs.IntrospectionServiceStub.class);
Mockito.when(oAuth2ServiceStub.getIntrospectionServiceStub()).thenReturn(introspectionStub);
ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
final String accessToken = "aaa-aaa-aaa-aaa";
// happy path - 200 - token is active
// //mocked response from /introspect service
OAuth2IntrospectionResponse introspectionResponse = new OAuth2IntrospectionResponse();
introspectionResponse.setActive(true);
introspectionResponse.setClientId(consumerKey);
// //expected response from key manager
AccessTokenInfo expectedTokenInfo = new AccessTokenInfo();
expectedTokenInfo.setTokenValid(introspectionResponse.isActive());
expectedTokenInfo.setAccessToken(accessToken);
expectedTokenInfo.setConsumerKey(introspectionResponse.getClientId());
Response introspectResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(introspectionResponse), feign.Util.UTF_8).build();
Mockito.when(oAuth2ServiceStub.getIntrospectionServiceStub()).thenReturn(introspectionStub);
Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(introspectResponse);
try {
AccessTokenInfo tokenMetaData = kmImpl.getTokenMetaData(accessToken);
Assert.assertEquals(tokenMetaData, expectedTokenInfo);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
// happy path - 200 - token is not active
// //mocked response from /introspect service
introspectionResponse = new OAuth2IntrospectionResponse();
introspectionResponse.setActive(false);
introspectionResponse.setClientId(consumerKey);
// //expected response from key manager
expectedTokenInfo = new AccessTokenInfo();
expectedTokenInfo.setTokenValid(introspectionResponse.isActive());
expectedTokenInfo.setErrorCode(KeyManagerConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
introspectResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(introspectionResponse), feign.Util.UTF_8).build();
Mockito.when(oAuth2ServiceStub.getIntrospectionServiceStub()).thenReturn(introspectionStub);
Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(introspectResponse);
try {
AccessTokenInfo tokenMetaData = kmImpl.getTokenMetaData(accessToken);
Assert.assertEquals(tokenMetaData, expectedTokenInfo);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
// error case - response is null
Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(null);
try {
kmImpl.getTokenMetaData(accessToken);
Assert.fail("Exception was expected, but wasn't thrown");
} catch (KeyManagementException ex) {
Assert.assertTrue(ex.getMessage().startsWith("Error occurred while introspecting access token. " + "Response is null"));
}
// error case - token response non-200
// //request to key manager
final int errorCode = 500;
introspectResponse = Response.builder().status(errorCode).headers(new HashMap<>()).body("backend error occurred", Util.UTF_8).build();
Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(introspectResponse);
try {
kmImpl.getTokenMetaData(accessToken);
Assert.fail("Exception was expected, but wasn't thrown");
} catch (KeyManagementException ex) {
Assert.assertTrue(ex.getMessage().startsWith("Token introspection request failed. HTTP error code: " + errorCode));
}
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByRefreshGrant.
@Test
public void testGetNewAccessTokenByRefreshGrant() throws Exception {
DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
// happy path - 200 - refresh grant type
// //request to key manager
AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.REFRESH_GRANT_TYPE, null, null, null, -1L, null, null, "xxx-refresh-token-xxx", null);
// //mocked response from /token service
OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
// //expected response from key manager
AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), Util.UTF_8).build();
Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), -2L, tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(newTokenResponse);
try {
AccessTokenInfo newToken = kmImpl.getNewAccessToken(tokenRequest);
Assert.assertEquals(newToken, accessTokenInfo);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByJWTGrant.
@Test
public void testGetNewAccessTokenByJWTGrant() throws Exception {
DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
// happy path - 200 - JWT grant type
// //request to key manager
AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.JWT_GRANT_TYPE, null, null, null, -2L, null, null, null, "xxx-assertion-xxx");
// //mocked response from /token service
OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
// //expected response from key manager
AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), Util.UTF_8).build();
Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateJWTGrantAccessToken(tokenRequest.getAssertion(), tokenRequest.getGrantType(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(newTokenResponse);
try {
AccessTokenInfo newToken = kmImpl.getNewAccessToken(tokenRequest);
Assert.assertEquals(newToken, accessTokenInfo);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
Aggregations