Search in sources :

Example 1 with TokenInfo

use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project product-apim by wso2.

the class TestUtil method generateToken.

private static void generateToken(String username, String password, String scopes) throws APIManagementException {
    if (StringUtils.isEmpty(clientId) | StringUtils.isEmpty(clientSecret)) {
        generateClient();
    }
    OAuth2ServiceStubs.TokenServiceStub tokenServiceStub = getOauth2Client();
    Response response = tokenServiceStub.generatePasswordGrantAccessToken(username, password, scopes, -1, clientId, clientSecret);
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        // 200 - Success
        logger.debug("A new access token is successfully generated.");
        try {
            OAuth2TokenInfo oAuth2TokenInfo = (OAuth2TokenInfo) new GsonDecoder().decode(response, OAuth2TokenInfo.class);
            accessTokenInfo = new TokenInfo(oAuth2TokenInfo.getAccessToken(), System.currentTimeMillis() + oAuth2TokenInfo.getExpiresIn());
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing token response", e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
        }
    }
}
Also used : Response(feign.Response) GsonDecoder(feign.gson.GsonDecoder) OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo) IOException(java.io.IOException) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)

Example 2 with TokenInfo

use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project product-apim by wso2.

the class APIMgtBaseIntegrationIT method init.

@BeforeClass
public void init() throws AMIntegrationTestException {
    TokenInfo tokenInfo = TestUtil.getToken("admin", "admin");
    apiPublisherClient = new ApiClient(TestUtil.OAUTH2_SECURITY).setBasePath("https://" + TestUtil.getIpAddressOfContainer() + ":9443/api/am/publisher/v1.0");
    apiPublisherClient.setAccessToken(tokenInfo.getToken(), tokenInfo.getExpiryTime());
    apiStoreClient = new org.wso2.carbon.apimgt.rest.integration.tests.store.ApiClient(TestUtil.OAUTH2_SECURITY).setBasePath("https://" + TestUtil.getIpAddressOfContainer() + ":9443/api/am/store/v1.0");
    apiStoreClient.setAccessToken(tokenInfo.getToken(), tokenInfo.getExpiryTime());
    apiAdminClient = new org.wso2.carbon.apimgt.rest.integration.tests.admin.ApiClient(TestUtil.OAUTH2_SECURITY).setBasePath("https://" + TestUtil.getIpAddressOfContainer() + ":9443/api/am/admin/v1.0");
    apiAdminClient.setAccessToken(tokenInfo.getToken(), tokenInfo.getExpiryTime());
}
Also used : TokenInfo(org.wso2.carbon.apimgt.rest.integration.tests.util.TokenInfo) BeforeClass(org.testng.annotations.BeforeClass)

Example 3 with TokenInfo

use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method getTokenMetaData.

@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws KeyManagementException {
    log.debug("Token introspection request is being sent.");
    Response response;
    try {
        response = oAuth2ServiceStubs.getIntrospectionServiceStub().introspectToken(accessToken);
    } catch (APIManagementException e) {
        throw new KeyManagementException("Error occurred while introspecting access token.", e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
    }
    if (response == null) {
        throw new KeyManagementException("Error occurred while introspecting access token. " + "Response is null", ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        log.debug("Token introspection is successful");
        try {
            OAuth2IntrospectionResponse introspectResponse = (OAuth2IntrospectionResponse) new GsonDecoder().decode(response, OAuth2IntrospectionResponse.class);
            AccessTokenInfo tokenInfo = new AccessTokenInfo();
            boolean active = introspectResponse.isActive();
            if (active) {
                tokenInfo.setTokenValid(true);
                tokenInfo.setAccessToken(accessToken);
                tokenInfo.setScopes(introspectResponse.getScope());
                tokenInfo.setConsumerKey(introspectResponse.getClientId());
                tokenInfo.setIssuedTime(introspectResponse.getIat());
                tokenInfo.setExpiryTime(introspectResponse.getExp());
                if (StringUtils.isNotEmpty(introspectResponse.getUsername())) {
                    tokenInfo.setEndUserName(introspectResponse.getUsername());
                }
                long validityPeriod = introspectResponse.getExp() - introspectResponse.getIat();
                tokenInfo.setValidityPeriod(validityPeriod);
            } else {
                tokenInfo.setTokenValid(false);
                log.error("Invalid or expired access token received.");
                tokenInfo.setErrorCode(KeyManagerConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
            }
            return tokenInfo;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing token introspection response", e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
        }
    } else {
        throw new KeyManagementException("Token introspection request failed. HTTP error code: " + response.status() + " Error Response Body: " + response.body().toString(), ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 4 with TokenInfo

use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo in project carbon-apimgt by wso2.

the class OAuth2Authenticator method validateTokenAndScopes.

private boolean validateTokenAndScopes(Request request, ServiceMethodInfo serviceMethodInfo, String accessToken) throws APIMgtSecurityException {
    // Map<String, String> tokenInfo = validateToken(accessToken);
    AccessTokenInfo accessTokenInfo = validateToken(accessToken);
    String restAPIResource = getRestAPIResource(request);
    // scope validation
    return validateScopes(request, serviceMethodInfo, accessTokenInfo.getScopes(), restAPIResource);
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo)

Example 5 with TokenInfo

use of org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo 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

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)9 HashMap (java.util.HashMap)4 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)4 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)4 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)4 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)3 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)3 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)3 Response (feign.Response)2 GsonDecoder (feign.gson.GsonDecoder)2 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 List (java.util.List)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 JSONObject (org.json.simple.JSONObject)2 OAuthTokenInfo (org.wso2.carbon.apimgt.api.OAuthTokenInfo)2 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)2 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)2 Scope (org.wso2.carbon.apimgt.api.model.Scope)2