use of org.wso2.carbon.apimgt.api.model.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;
}
use of org.wso2.carbon.apimgt.api.model.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.apimgt.api.model.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.apimgt.api.model.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.apimgt.api.model.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;
}
Aggregations