Search in sources :

Example 1 with TokenInfo

use of org.wso2.carbon.apimgt.rest.integration.tests.util.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.rest.integration.tests.util.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.rest.integration.tests.util.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.rest.integration.tests.util.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.rest.integration.tests.util.TokenInfo in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetTokens.

@Test
public void testGetTokens() throws Exception {
    // Happy Path - 200 - Authorization code grant type
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    // // Mocked response from DCR endpoint
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setClientSecret("xxx-client-secret-xxx");
    // // Expected response object from KeyManager
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken("xxx-access-token-xxx");
    tokenInfo.setScopes("apim:subscribe openid");
    tokenInfo.setRefreshToken("xxx-refresh-token-xxx");
    tokenInfo.setIdToken("xxx-id-token-xxx");
    tokenInfo.setValidityPeriod(-2L);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    // // Actual response - When authorization code is not null
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForValidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, "xxx-auth-code-xxx", null, null);
    Assert.assertEquals(tokenInfoResponseForValidAuthCode, tokenInfo);
    // Error Path - 500 - Authorization code grant type
    // // When an error occurred - Eg: Access denied
    AccessTokenInfo emptyTokenInfo = new AccessTokenInfo();
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(emptyTokenInfo);
    AccessTokenInfo tokenInfoResponseForInvalidAuthCode = new AccessTokenInfo();
    try {
        tokenInfoResponseForInvalidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, null, null, null);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "No Authorization Code available.");
        Assert.assertEquals(tokenInfoResponseForInvalidAuthCode, emptyTokenInfo);
    }
    // Happy Path - 200 - Password grant type
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForPasswordGrant = authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
    Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
    // Error Path - When token generation fails and throws APIManagementException
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenThrow(KeyManagementException.class).thenReturn(tokenInfo);
    try {
        authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while receiving tokens for OAuth application : store");
    }
    // Happy Path - 200 - Refresh grant type
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForRefreshGrant = authenticatorService.getTokens("store", "refresh_token", null, null, null, 0, null, null, null);
    Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
    // Happy Path - 200 - JWT grant type
    // Multi-Environment Overview configuration
    multiEnvironmentOverview.setEnabled(true);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    String userFromIdentityProvider = "admin-user";
    Mockito.when(identityProvider.getIdOfUser(Mockito.anyString())).thenThrow(IdentityProviderException.class);
    Mockito.doReturn("xxx-admin-user-id-xxx").when(identityProvider).getIdOfUser(userFromIdentityProvider);
    // A valid jwt with user "admin-user"
    String idTokenWith_adminUser = "xxx+header+xxx.eyJzdWIiOiJhZG1pbi11c2VyIn0.xxx+signature+xxx";
    tokenInfo.setIdToken(idTokenWith_adminUser);
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForValidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
    Assert.assertEquals(tokenInfoResponseForValidJWTGrant, tokenInfo);
    // Error Path - When invalid user in JWT Token
    // A valid jwt with user "John"
    String idTokenWith_johnUser = "xxx+header+xxx.eyJzdWIiOiJKb2huIn0.xxx+signature+xxx";
    tokenInfo.setIdToken(idTokenWith_johnUser);
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    try {
        AccessTokenInfo tokenInfoResponseForInvalidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
        Assert.assertEquals(tokenInfoResponseForInvalidJWTGrant, tokenInfo);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "User John does not exists in this environment.");
    }
}
Also used : IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Aggregations

KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)3 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)3 Response (feign.Response)2 GsonDecoder (feign.gson.GsonDecoder)2 IOException (java.io.IOException)2 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)2 Test (org.junit.Test)1 BeforeClass (org.testng.annotations.BeforeClass)1 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)1 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)1 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)1 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)1 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)1 APIMConfigurationService (org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService)1 EnvironmentConfigurations (org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations)1 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)1 SystemApplicationDao (org.wso2.carbon.apimgt.core.dao.SystemApplicationDao)1 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)1 APIMAppConfigurationService (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService)1 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)1