Search in sources :

Example 11 with AccessTokenInfo

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);
    }
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IntrospectInfo(org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectInfo)

Example 12 with AccessTokenInfo

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;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TokenInfo(org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo)

Example 13 with AccessTokenInfo

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;
}
Also used : ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ParseException(org.json.simple.parser.ParseException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 14 with AccessTokenInfo

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;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo)

Example 15 with AccessTokenInfo

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;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Aggregations

AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)18 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)12 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)12 Response (feign.Response)9 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)8 Gson (com.google.gson.Gson)7 Test (org.junit.Test)7 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)7 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)7 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)7 HashMap (java.util.HashMap)6 Test (org.testng.annotations.Test)6 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)6 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)6 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)6 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)6 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)5