use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo 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.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class AMDefaultKeyManagerImplTest method testTokenUnlimitedExpirationTime.
@Test
public void testTokenUnlimitedExpirationTime() throws KeyManagerClientException, APIManagementException {
String accessToken = "155ddde3-68db-35b1-82dc-1247616b2da9";
IntrospectInfo response = new IntrospectInfo();
response.setActive(true);
response.setExpiry(Long.MAX_VALUE);
response.setIat(new Date().getTime());
Mockito.when(introspectionClient.introspect(accessToken)).thenReturn(response);
AccessTokenInfo info = keyManager.getTokenMetaData(accessToken);
Assert.assertEquals(Long.MAX_VALUE, info.getValidityPeriod());
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo 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.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdKeysKeyTypeGenerateTokenPost.
@Override
public Response applicationsApplicationIdKeysKeyTypeGenerateTokenPost(String applicationId, String keyType, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) {
try {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application != null) {
if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyType(applicationId, keyType);
if (appKey != null) {
String jsonInput = null;
String grantType;
if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
} else {
grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
}
try {
// verify that the provided jsonInput is a valid json
if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
jsonInput = validateAdditionalParameters(grantType, body);
}
} catch (JsonProcessingException | ParseException | ClassCastException e) {
RestApiUtil.handleBadRequest("Error while generating " + keyType + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
}
if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
appKey.setConsumerSecret(body.getConsumerSecret());
}
String[] scopes = body.getScopes().toArray(new String[0]);
AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, APIConstants.KeyManager.DEFAULT_KEY_MANAGER, grantType);
ApplicationTokenDTO appToken = new ApplicationTokenDTO();
appToken.setAccessToken(response.getAccessToken());
appToken.setTokenScopes(Arrays.asList(response.getScopes()));
appToken.setValidityTime(response.getValidityPeriod());
return Response.ok().entity(appToken).build();
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyType, log);
}
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while generating " + keyType + " token for application " + applicationId, e, log);
}
return null;
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class AccessTokenGenerator method generateNewAccessToken.
private AccessTokenInfo generateNewAccessToken(String[] scopes) {
try {
String tokenEndpoint;
int serverPort;
URL oauthURL;
if (StringUtils.isNotEmpty(this.tokenEndpoint)) {
tokenEndpoint = this.tokenEndpoint;
oauthURL = new URL(tokenEndpoint);
serverPort = oauthURL.getPort();
} else {
oauthURL = new URL(oauthUrl);
serverPort = oauthURL.getPort();
tokenEndpoint = oauthUrl.concat("/token");
}
String serverProtocol = oauthURL.getProtocol();
HttpPost request = new HttpPost(tokenEndpoint);
HttpClient httpClient = APIUtil.getHttpClient(serverPort, serverProtocol);
byte[] credentials = org.apache.commons.codec.binary.Base64.encodeBase64((consumerKey + ":" + consumerSecret).getBytes(StandardCharsets.UTF_8));
request.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
request.setHeader(APIConstants.CONTENT_TYPE_HEADER, APIConstants.CONTENT_TYPE_APPLICATION_FORM);
List<BasicNameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair(APIConstants.TOKEN_GRANT_TYPE_KEY, APIConstants.GRANT_TYPE_VALUE));
if (scopes != null && scopes.length > 0) {
urlParameters.add(new BasicNameValuePair(APIConstants.OAUTH_RESPONSE_TOKEN_SCOPE, String.join(" ", scopes)));
}
request.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse httpResponse = httpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String payload = EntityUtils.toString(httpResponse.getEntity());
JSONObject response = new JSONObject(payload);
String accessToken = (String) response.get(APIConstants.OAUTH_RESPONSE_ACCESSTOKEN);
int validityPeriod = (Integer) response.get(APIConstants.OAUTH_RESPONSE_EXPIRY_TIME) * 1000;
long expiryTime = System.currentTimeMillis() + validityPeriod;
if (log.isDebugEnabled()) {
log.debug("Successfully received an access token which expires in " + expiryTime);
}
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
accessTokenInfo.setAccessToken(accessToken);
accessTokenInfo.setIssuedTime(System.currentTimeMillis());
accessTokenInfo.setValidityPeriod(validityPeriod);
return accessTokenInfo;
} else {
log.error("Error occurred when generating a new Access token. Server responded with " + httpResponse.getStatusLine().getStatusCode());
}
} catch (IOException e) {
log.error("Error occurred when generating a new Access token", e);
}
return null;
}
Aggregations