use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.
the class AuthenticatorServiceTestCase method testGetTokens.
@Test
public void testGetTokens() throws Exception {
// Happy Path - 200 - Authorization code grant type
APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
// // Mocked response from DCR endpoint
OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
oAuthApplicationInfo.setClientSecret("xxx-client-secret-xxx");
// // Expected response object from KeyManager
AccessTokenInfo tokenInfo = new AccessTokenInfo();
tokenInfo.setAccessToken("xxx-access-token-xxx");
tokenInfo.setScopes("apim:subscribe openid");
tokenInfo.setRefreshToken("xxx-refresh-token-xxx");
tokenInfo.setIdToken("xxx-id-token-xxx");
tokenInfo.setValidityPeriod(-2L);
KeyManager keyManager = Mockito.mock(KeyManager.class);
SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
// // Actual response - When authorization code is not null
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
AccessTokenInfo tokenInfoResponseForValidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, "xxx-auth-code-xxx", null, null);
Assert.assertEquals(tokenInfoResponseForValidAuthCode, tokenInfo);
// Error Path - 500 - Authorization code grant type
// // When an error occurred - Eg: Access denied
AccessTokenInfo emptyTokenInfo = new AccessTokenInfo();
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(emptyTokenInfo);
AccessTokenInfo tokenInfoResponseForInvalidAuthCode = new AccessTokenInfo();
try {
tokenInfoResponseForInvalidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, null, null, null);
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "No Authorization Code available.");
Assert.assertEquals(tokenInfoResponseForInvalidAuthCode, emptyTokenInfo);
}
// Happy Path - 200 - Password grant type
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
AccessTokenInfo tokenInfoResponseForPasswordGrant = authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
// Error Path - When token generation fails and throws APIManagementException
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenThrow(KeyManagementException.class).thenReturn(tokenInfo);
try {
authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "Error while receiving tokens for OAuth application : store");
}
// Happy Path - 200 - Refresh grant type
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
AccessTokenInfo tokenInfoResponseForRefreshGrant = authenticatorService.getTokens("store", "refresh_token", null, null, null, 0, null, null, null);
Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
// Happy Path - 200 - JWT grant type
// Multi-Environment Overview configuration
multiEnvironmentOverview.setEnabled(true);
IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
String userFromIdentityProvider = "admin-user";
Mockito.when(identityProvider.getIdOfUser(Mockito.anyString())).thenThrow(IdentityProviderException.class);
Mockito.doReturn("xxx-admin-user-id-xxx").when(identityProvider).getIdOfUser(userFromIdentityProvider);
// A valid jwt with user "admin-user"
String idTokenWith_adminUser = "xxx+header+xxx.eyJzdWIiOiJhZG1pbi11c2VyIn0.xxx+signature+xxx";
tokenInfo.setIdToken(idTokenWith_adminUser);
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
AccessTokenInfo tokenInfoResponseForValidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
Assert.assertEquals(tokenInfoResponseForValidJWTGrant, tokenInfo);
// Error Path - When invalid user in JWT Token
// A valid jwt with user "John"
String idTokenWith_johnUser = "xxx+header+xxx.eyJzdWIiOiJKb2huIn0.xxx+signature+xxx";
tokenInfo.setIdToken(idTokenWith_johnUser);
Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
try {
AccessTokenInfo tokenInfoResponseForInvalidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
Assert.assertEquals(tokenInfoResponseForInvalidJWTGrant, tokenInfo);
} catch (APIManagementException e) {
Assert.assertEquals(e.getMessage(), "User John does not exists in this environment.");
}
}
use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.
the class OAuthOpaqueAuthenticatorImpl method getTokenMetaData.
@MethodStats
public OAuthTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
OAuthTokenInfo tokenInfo = new OAuthTokenInfo();
OAuth2TokenValidationRequestDTO requestDTO = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken token = requestDTO.new OAuth2AccessToken();
token.setIdentifier(accessToken);
token.setTokenType("bearer");
requestDTO.setAccessToken(token);
OAuth2TokenValidationRequestDTO.TokenValidationContextParam[] contextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
requestDTO.setContext(contextParams);
OAuth2ClientApplicationDTO clientApplicationDTO = findOAuthConsumerIfTokenIsValid(requestDTO);
OAuth2TokenValidationResponseDTO responseDTO = clientApplicationDTO.getAccessTokenValidationResponse();
if (!responseDTO.isValid()) {
tokenInfo.setTokenValid(responseDTO.isValid());
log.error("Invalid OAuth Token : " + responseDTO.getErrorMsg());
return tokenInfo;
}
tokenInfo.setTokenValid(responseDTO.isValid());
tokenInfo.setEndUserName(responseDTO.getAuthorizedUser());
tokenInfo.setConsumerKey(clientApplicationDTO.getConsumerKey());
// Convert Expiry Time to milliseconds.
if (responseDTO.getExpiryTime() == Long.MAX_VALUE) {
tokenInfo.setValidityPeriod(Long.MAX_VALUE);
} else {
tokenInfo.setValidityPeriod(responseDTO.getExpiryTime() * 1000L);
}
tokenInfo.setIssuedTime(System.currentTimeMillis());
tokenInfo.setScopes(responseDTO.getScope());
return tokenInfo;
}
use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandler method validateToken.
@Override
public boolean validateToken(TokenValidationContext validationContext) throws APIKeyMgtException {
// If validationInfoDTO is taken from cache, validity of the cached infoDTO is checked with each request.
if (validationContext.isCacheHit()) {
APIKeyValidationInfoDTO infoDTO = validationContext.getValidationInfoDTO();
// TODO: This should only happen in GW
boolean tokenExpired = APIUtil.isAccessTokenExpired(infoDTO);
if (tokenExpired) {
infoDTO.setAuthorized(false);
infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
log.debug("Token " + validationContext.getAccessToken() + " expired.");
return false;
} else {
return true;
}
}
if (StringUtils.isEmpty(validationContext.getAccessToken())) {
APIKeyValidationInfoDTO infoDTO = validationContext.getValidationInfoDTO();
infoDTO.setAuthorized(false);
infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
log.debug("Token Not available");
return false;
}
try {
AccessTokenInfo tokenInfo = getAccessTokenInfo(validationContext);
if (tokenInfo == null) {
return false;
}
// Setting TokenInfo in validationContext. Methods down in the chain can use TokenInfo.
validationContext.setTokenInfo(tokenInfo);
// TODO: Eliminate use of APIKeyValidationInfoDTO if possible
APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
validationContext.setValidationInfoDTO(apiKeyValidationInfoDTO);
if (!tokenInfo.isTokenValid()) {
apiKeyValidationInfoDTO.setAuthorized(false);
if (tokenInfo.getErrorcode() > 0) {
apiKeyValidationInfoDTO.setValidationStatus(tokenInfo.getErrorcode());
} else {
apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_GENERAL_ERROR);
}
return false;
}
apiKeyValidationInfoDTO.setKeyManager(tokenInfo.getKeyManager());
apiKeyValidationInfoDTO.setAuthorized(tokenInfo.isTokenValid());
apiKeyValidationInfoDTO.setEndUserName(tokenInfo.getEndUserName());
apiKeyValidationInfoDTO.setConsumerKey(tokenInfo.getConsumerKey());
apiKeyValidationInfoDTO.setIssuedTime(tokenInfo.getIssuedTime());
apiKeyValidationInfoDTO.setValidityPeriod(tokenInfo.getValidityPeriod());
if (tokenInfo.getScopes() != null) {
Set<String> scopeSet = new HashSet<String>(Arrays.asList(tokenInfo.getScopes()));
apiKeyValidationInfoDTO.setScopes(scopeSet);
}
return tokenInfo.isTokenValid();
} catch (APIManagementException e) {
log.error("Error while obtaining Token Metadata from Authorization Server", e);
throw new APIKeyMgtException("Error while obtaining Token Metadata from Authorization Server");
}
}
use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.
the class AbstractAPIManager method getApplicationKeys.
/**
* Returns the key associated with given application id.
*
* @param applicationId Id of the Application.
* @return APIKey The key of the application.
* @throws APIManagementException
*/
protected Set<APIKey> getApplicationKeys(int applicationId, String xWso2Tenant) throws APIManagementException {
Set<APIKey> apiKeyList = apiMgtDAO.getKeyMappingsFromApplicationId(applicationId);
if (StringUtils.isNotEmpty(xWso2Tenant)) {
int tenantId = APIUtil.getInternalOrganizationId(xWso2Tenant);
// To handle choreo scenario. due to keymanagers are not per organization atm. using ST
if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
xWso2Tenant = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
}
Set<APIKey> resultantApiKeyList = new HashSet<>();
for (APIKey apiKey : apiKeyList) {
String keyManagerName = apiKey.getKeyManager();
String consumerKey = apiKey.getConsumerKey();
String tenantDomain = this.tenantDomain;
if (StringUtils.isNotEmpty(xWso2Tenant)) {
tenantDomain = xWso2Tenant;
}
KeyManagerConfigurationDTO keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
if (keyManagerConfigurationDTO == null) {
keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
if (keyManagerConfigurationDTO != null) {
keyManagerName = keyManagerConfigurationDTO.getName();
} else {
log.error("Key Manager: " + keyManagerName + " not found in database.");
continue;
}
}
if (tenantDomain != null && !tenantDomain.equalsIgnoreCase(keyManagerConfigurationDTO.getOrganization())) {
continue;
}
KeyManager keyManager = null;
if (keyManagerConfigurationDTO.isEnabled()) {
keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
} else {
continue;
}
apiKey.setKeyManager(keyManagerConfigurationDTO.getName());
if (StringUtils.isNotEmpty(consumerKey)) {
if (keyManager != null) {
if (APIConstants.OAuthAppMode.MAPPED.name().equalsIgnoreCase(apiKey.getCreateMode()) && !isOauthAppValidation()) {
resultantApiKeyList.add(apiKey);
} else {
OAuthApplicationInfo oAuthApplicationInfo = null;
try {
oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
} catch (APIManagementException e) {
log.error("Error while retrieving Application Information", e);
continue;
}
if (StringUtils.isNotEmpty(apiKey.getAppMetaData())) {
OAuthApplicationInfo storedOAuthApplicationInfo = new Gson().fromJson(apiKey.getAppMetaData(), OAuthApplicationInfo.class);
if (oAuthApplicationInfo == null) {
oAuthApplicationInfo = storedOAuthApplicationInfo;
} else {
if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL())) {
oAuthApplicationInfo.setCallBackURL(storedOAuthApplicationInfo.getCallBackURL());
}
if ("null".equalsIgnoreCase(oAuthApplicationInfo.getCallBackURL())) {
oAuthApplicationInfo.setCallBackURL("");
}
if (oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) == null && storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) != null) {
if (storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) instanceof String) {
oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, ((String) storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES)).replace(",", " "));
} else {
oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
}
}
if (StringUtils.isEmpty(oAuthApplicationInfo.getClientSecret()) && StringUtils.isNotEmpty(storedOAuthApplicationInfo.getClientSecret())) {
oAuthApplicationInfo.setClientSecret(storedOAuthApplicationInfo.getClientSecret());
}
}
}
AccessTokenInfo tokenInfo = keyManager.getAccessTokenByConsumerKey(consumerKey);
if (oAuthApplicationInfo != null) {
apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
apiKey.setCallbackUrl(oAuthApplicationInfo.getCallBackURL());
apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
if (oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES) != null) {
apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
}
}
if (tokenInfo != null) {
apiKey.setAccessToken(tokenInfo.getAccessToken());
apiKey.setValidityPeriod(tokenInfo.getValidityPeriod());
} else {
if (log.isDebugEnabled()) {
log.debug("Access token does not exist for Consumer Key: " + consumerKey);
}
}
resultantApiKeyList.add(apiKey);
}
} else {
log.error("Key Manager " + keyManagerName + " not initialized in tenant " + tenantDomain);
}
} else {
resultantApiKeyList.add(apiKey);
}
}
return resultantApiKeyList;
}
use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.
the class AbstractApplicationRegistrationWorkflowExecutor method dogenerateKeysForApplication.
public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO) throws APIManagementException {
log.debug("Registering Application and creating an Access Token... ");
Application application = workflowDTO.getApplication();
Subscriber subscriber = application.getSubscriber();
ApiMgtDAO dao = ApiMgtDAO.getInstance();
if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
dao.populateAppRegistrationWorkflowDTO(workflowDTO);
}
try {
// get new key manager
// Here the default flow is set expecting an ID as the keymanager as this flow only involves new applications
String keyManagerId = workflowDTO.getKeyManager();
KeyManagerConfigurationDTO km = dao.getKeyManagerConfigurationByUUID(keyManagerId);
String tenantDomain = km.getOrganization();
String keyManagerName = km.getName();
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
if (keyManager == null) {
throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
}
workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().setClientName(application.getName());
// set applications attributes to the oAuthApplicationInfo
workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
// createApplication on oAuthorization server.
OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());
// update associateApplication
ApplicationUtils.updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerId);
// change create application status in to completed.
dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED, workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerId);
workflowDTO.setApplicationInfo(oAuthApplication);
AccessTokenInfo tokenInfo;
Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
} else {
tokenInfo = new AccessTokenInfo();
tokenInfo.setAccessToken("");
tokenInfo.setValidityPeriod(0L);
String[] noScopes = new String[] { "N/A" };
tokenInfo.setScope(noScopes);
oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
}
workflowDTO.setAccessTokenInfo(tokenInfo);
} catch (Exception e) {
APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
}
}
Aggregations