use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class AMDefaultKeyManagerImpl method getTokenMetaData.
@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
AccessTokenInfo tokenInfo = new AccessTokenInfo();
try {
IntrospectInfo introspectInfo = introspectionClient.introspect(accessToken);
tokenInfo.setAccessToken(accessToken);
boolean isActive = introspectInfo.isActive();
if (!isActive) {
tokenInfo.setTokenValid(false);
tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
return tokenInfo;
}
tokenInfo.setTokenValid(true);
if (introspectInfo.getIat() > 0 && introspectInfo.getExpiry() > 0) {
if (introspectInfo.getExpiry() != Long.MAX_VALUE) {
long validityPeriod = introspectInfo.getExpiry() - introspectInfo.getIat();
tokenInfo.setValidityPeriod(validityPeriod * 1000L);
} else {
tokenInfo.setValidityPeriod(Long.MAX_VALUE);
}
tokenInfo.setIssuedTime(introspectInfo.getIat() * 1000L);
}
if (StringUtils.isNotEmpty(introspectInfo.getScope())) {
String[] scopes = introspectInfo.getScope().split(" ");
tokenInfo.setScope(scopes);
}
tokenInfo.setConsumerKey(introspectInfo.getClientId());
String username = introspectInfo.getUsername();
if (!StringUtils.isEmpty(username)) {
tokenInfo.setEndUserName(username);
}
return tokenInfo;
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred in token introspection!", e);
}
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class AMDefaultKeyManagerImpl method getNewApplicationAccessToken.
@Override
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException {
AccessTokenInfo tokenInfo;
if (tokenRequest == null) {
log.warn("No information available to generate Token.");
return null;
}
// When validity time set to a negative value, a token is considered never to expire.
if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) {
// Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator)
tokenRequest.setValidityPeriod(-2L);
}
// Generate New Access Token
String scopes = String.join(" ", tokenRequest.getScope());
TokenInfo tokenResponse;
try {
String credentials = tokenRequest.getClientId() + ':' + tokenRequest.getClientSecret();
String authToken = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
if (APIConstants.OAuthConstants.TOKEN_EXCHANGE.equals(tokenRequest.getGrantType())) {
tokenResponse = authClient.generate(tokenRequest.getClientId(), tokenRequest.getClientSecret(), tokenRequest.getGrantType(), scopes, (String) tokenRequest.getRequestParam(APIConstants.OAuthConstants.SUBJECT_TOKEN), APIConstants.OAuthConstants.JWT_TOKEN_TYPE);
} else {
tokenResponse = authClient.generate(authToken, GRANT_TYPE_VALUE, scopes);
}
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred while calling token endpoint - " + e.getReason(), e);
}
tokenInfo = new AccessTokenInfo();
if (StringUtils.isNotEmpty(tokenResponse.getScope())) {
tokenInfo.setScope(tokenResponse.getScope().split(" "));
} else {
tokenInfo.setScope(new String[0]);
}
tokenInfo.setAccessToken(tokenResponse.getToken());
tokenInfo.setValidityPeriod(tokenResponse.getExpiry());
return tokenInfo;
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost.
@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost(String applicationId, String keyMappingId, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application != null) {
if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
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 " + appKey.getKeyType() + " 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]);
try {
AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, appKey.getKeyManager(), grantType);
ApplicationTokenDTO appToken = new ApplicationTokenDTO();
appToken.setAccessToken(response.getAccessToken());
if (response.getScopes() != null) {
appToken.setTokenScopes(Arrays.asList(response.getScopes()));
}
appToken.setValidityTime(response.getValidityPeriod());
return Response.ok().entity(appToken).build();
} catch (APIManagementException e) {
Long errorCode = e.getErrorHandler() != null ? e.getErrorHandler().getErrorCode() : ExceptionCodes.INTERNAL_ERROR.getErrorCode();
RestApiUtil.handleBadRequest(e.getMessage(), errorCode, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyMappingId, log);
}
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
return null;
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class AccessTokenGenerator method getAccessToken.
public String getAccessToken(String[] scopes) {
String scopeHash = getScopeHash(scopes);
AccessTokenInfo accessTokenInfo = accessTokenInfoMap.get(scopeHash);
if (accessTokenInfo != null) {
long expiryTime = accessTokenInfo.getIssuedTime() + accessTokenInfo.getValidityPeriod();
// buffer time is set to 20 seconds
long buffer = 20000;
if (System.currentTimeMillis() > expiryTime) {
if (log.isDebugEnabled()) {
log.debug("Access token expired. New token requested");
}
accessTokenInfoMap.remove(scopeHash);
accessTokenInfo = generateNewAccessToken(scopes);
accessTokenInfoMap.put(scopeHash, accessTokenInfo);
} else if (buffer > (expiryTime - System.currentTimeMillis())) {
if (log.isDebugEnabled()) {
log.debug("Access Token will expire soon. Generated a new Token after revoking the previous");
}
revokeAccessToken(accessTokenInfo.getAccessToken());
accessTokenInfoMap.remove(scopeHash);
accessTokenInfo = generateNewAccessToken(scopes);
accessTokenInfoMap.put(scopeHash, accessTokenInfo);
} else {
if (log.isDebugEnabled()) {
log.debug("Valid Access Token already available for the provided application");
}
return accessTokenInfo.getAccessToken();
}
} else {
accessTokenInfo = generateNewAccessToken(scopes);
}
if (accessTokenInfo != null) {
accessTokenInfoMap.put(scopeHash, accessTokenInfo);
return accessTokenInfo.getAccessToken();
}
return null;
}
use of org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo in project carbon-apimgt by wso2.
the class AbstractKeyValidationHandler method validateSubscription.
@Override
public boolean validateSubscription(TokenValidationContext validationContext) throws APIKeyMgtException {
if (validationContext == null || validationContext.getValidationInfoDTO() == null) {
return false;
}
if (validationContext.isCacheHit()) {
return true;
}
APIKeyValidationInfoDTO dto = validationContext.getValidationInfoDTO();
if (validationContext.getTokenInfo() != null) {
if (validationContext.getTokenInfo().isApplicationToken()) {
dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
} else {
dto.setUserType(APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN);
}
AccessTokenInfo tokenInfo = validationContext.getTokenInfo();
// Application Token
if (!hasTokenRequiredAuthLevel(validationContext.getRequiredAuthenticationLevel(), tokenInfo)) {
dto.setAuthorized(false);
dto.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE);
return false;
}
}
boolean state = false;
try {
if (log.isDebugEnabled()) {
log.debug("Before validating subscriptions : " + dto);
log.debug("Validation Info : { context : " + validationContext.getContext() + " , " + "version : " + validationContext.getVersion() + " , consumerKey : " + dto.getConsumerKey() + " }");
}
state = validateSubscriptionDetails(validationContext.getContext(), validationContext.getVersion(), dto.getConsumerKey(), dto.getKeyManager(), dto);
if (log.isDebugEnabled()) {
log.debug("After validating subscriptions : " + dto);
}
} catch (APIManagementException e) {
log.error("Error Occurred while validating subscription.", e);
}
return state;
}
Aggregations