Search in sources :

Example 1 with OAuth2IntrospectionResponse

use of org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse 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 2 with OAuth2IntrospectionResponse

use of org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetTokenMetaData.

@Test
public void testGetTokenMetaData() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.IntrospectionServiceStub introspectionStub = Mockito.mock(OAuth2ServiceStubs.IntrospectionServiceStub.class);
    Mockito.when(oAuth2ServiceStub.getIntrospectionServiceStub()).thenReturn(introspectionStub);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    final String accessToken = "aaa-aaa-aaa-aaa";
    // happy path - 200 - token is active
    // //mocked response from /introspect service
    OAuth2IntrospectionResponse introspectionResponse = new OAuth2IntrospectionResponse();
    introspectionResponse.setActive(true);
    introspectionResponse.setClientId(consumerKey);
    // //expected response from key manager
    AccessTokenInfo expectedTokenInfo = new AccessTokenInfo();
    expectedTokenInfo.setTokenValid(introspectionResponse.isActive());
    expectedTokenInfo.setAccessToken(accessToken);
    expectedTokenInfo.setConsumerKey(introspectionResponse.getClientId());
    Response introspectResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(introspectionResponse), feign.Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getIntrospectionServiceStub()).thenReturn(introspectionStub);
    Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(introspectResponse);
    try {
        AccessTokenInfo tokenMetaData = kmImpl.getTokenMetaData(accessToken);
        Assert.assertEquals(tokenMetaData, expectedTokenInfo);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // happy path - 200 - token is not active
    // //mocked response from /introspect service
    introspectionResponse = new OAuth2IntrospectionResponse();
    introspectionResponse.setActive(false);
    introspectionResponse.setClientId(consumerKey);
    // //expected response from key manager
    expectedTokenInfo = new AccessTokenInfo();
    expectedTokenInfo.setTokenValid(introspectionResponse.isActive());
    expectedTokenInfo.setErrorCode(KeyManagerConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
    introspectResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(introspectionResponse), feign.Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getIntrospectionServiceStub()).thenReturn(introspectionStub);
    Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(introspectResponse);
    try {
        AccessTokenInfo tokenMetaData = kmImpl.getTokenMetaData(accessToken);
        Assert.assertEquals(tokenMetaData, expectedTokenInfo);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - response is null
    Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(null);
    try {
        kmImpl.getTokenMetaData(accessToken);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while introspecting access token. " + "Response is null"));
    }
    // error case - token response non-200
    // //request to key manager
    final int errorCode = 500;
    introspectResponse = Response.builder().status(errorCode).headers(new HashMap<>()).body("backend error occurred", Util.UTF_8).build();
    Mockito.when(introspectionStub.introspectToken(accessToken)).thenReturn(introspectResponse);
    try {
        kmImpl.getTokenMetaData(accessToken);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Token introspection request failed. HTTP error code: " + errorCode));
    }
}
Also used : HashMap(java.util.HashMap) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Gson(com.google.gson.Gson) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) Test(org.testng.annotations.Test)

Aggregations

Response (feign.Response)2 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)2 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)2 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)2 Gson (com.google.gson.Gson)1 GsonDecoder (feign.gson.GsonDecoder)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 Test (org.testng.annotations.Test)1 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)1 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)1 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)1 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)1