Search in sources :

Example 16 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.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 17 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class APIStoreImpl method generateApplicationToken.

@Override
public ApplicationToken generateApplicationToken(String clientId, String clientSecret, String scopes, long validityPeriod, String tokenToBeRevoked) throws APIManagementException {
    log.debug("Generating a new application access token");
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    accessTokenRequest.setClientId(clientId);
    accessTokenRequest.setClientSecret(clientSecret);
    accessTokenRequest.setGrantType(KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE);
    if (StringUtils.isEmpty(scopes)) {
        scopes = KeyManagerConstants.OAUTH2_DEFAULT_SCOPE;
    }
    accessTokenRequest.setScopes(scopes);
    accessTokenRequest.setValidityPeriod(validityPeriod);
    accessTokenRequest.setTokenToRevoke(tokenToBeRevoked);
    AccessTokenInfo newToken = getKeyManager().getNewAccessToken(accessTokenRequest);
    ApplicationToken applicationToken = new ApplicationToken();
    applicationToken.setAccessToken(newToken.getAccessToken());
    applicationToken.setValidityPeriod(newToken.getValidityPeriod());
    applicationToken.setScopes(newToken.getScopes());
    log.debug("Successfully created a new application access token.");
    return applicationToken;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) ApplicationToken(org.wso2.carbon.apimgt.core.models.ApplicationToken)

Example 18 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo 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)

Example 19 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByRefreshGrant.

@Test
public void testGetNewAccessTokenByRefreshGrant() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200 - refresh grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.REFRESH_GRANT_TYPE, null, null, null, -1L, null, null, "xxx-refresh-token-xxx", null);
    // //mocked response from /token service
    OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
    // //expected response from key manager
    AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
    Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), -2L, tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(newTokenResponse);
    try {
        AccessTokenInfo newToken = kmImpl.getNewAccessToken(tokenRequest);
        Assert.assertEquals(newToken, accessTokenInfo);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) Gson(com.google.gson.Gson) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) 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) Test(org.testng.annotations.Test)

Example 20 with AccessTokenInfo

use of org.wso2.carbon.apimgt.api.model.AccessTokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByJWTGrant.

@Test
public void testGetNewAccessTokenByJWTGrant() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200 - JWT grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.JWT_GRANT_TYPE, null, null, null, -2L, null, null, null, "xxx-assertion-xxx");
    // //mocked response from /token service
    OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
    // //expected response from key manager
    AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
    Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateJWTGrantAccessToken(tokenRequest.getAssertion(), tokenRequest.getGrantType(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(newTokenResponse);
    try {
        AccessTokenInfo newToken = kmImpl.getNewAccessToken(tokenRequest);
        Assert.assertEquals(newToken, accessTokenInfo);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) Gson(com.google.gson.Gson) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) 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) Test(org.testng.annotations.Test)

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