Search in sources :

Example 1 with MultiEnvironmentOverview

use of org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview in project carbon-apimgt by wso2.

the class AuthenticatorService method getTokens.

/**
 * This method returns the access tokens for a given application.
 *
 * @param appName           Name of the application which needs to get tokens
 * @param grantType         Grant type of the application
 * @param userName          User name of the user
 * @param password          Password of the user
 * @param refreshToken      Refresh token
 * @param validityPeriod    Validity period of tokens
 * @param authorizationCode Authorization Code
 * @return AccessTokenInfo - An object with the generated access token information
 * @throws APIManagementException When receiving access tokens fails
 */
public AccessTokenInfo getTokens(String appName, String grantType, String userName, String password, String refreshToken, long validityPeriod, String authorizationCode, String assertion, IdentityProvider identityProvider) throws APIManagementException {
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    MultiEnvironmentOverview multiEnvironmentOverviewConfigs = apimConfigurationService.getEnvironmentConfigurations().getMultiEnvironmentOverview();
    boolean isMultiEnvironmentOverviewEnabled = multiEnvironmentOverviewConfigs.isEnabled();
    // Get scopes of the application
    String scopes = getApplicationScopes(appName);
    log.debug("Set scopes for {} application using swagger definition.", appName);
    // TODO: Get Consumer Key & Secret without creating a new app, from the IS side
    Map<String, String> consumerKeySecretMap = getConsumerKeySecret(appName);
    log.debug("Received consumer key & secret for {} application.", appName);
    try {
        if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(grantType)) {
            // Access token for authorization code grant type
            APIMAppConfigurations appConfigs = apimAppConfigurationService.getApimAppConfigurations();
            String callBackURL = appConfigs.getApimBaseUrl() + AuthenticatorConstants.AUTHORIZATION_CODE_CALLBACK_URL + appName;
            if (authorizationCode != null) {
                // Get Access & Refresh Tokens
                accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
                accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
                accessTokenRequest.setGrantType(grantType);
                accessTokenRequest.setAuthorizationCode(authorizationCode);
                accessTokenRequest.setScopes(scopes);
                accessTokenRequest.setValidityPeriod(validityPeriod);
                accessTokenRequest.setCallbackURI(callBackURL);
                accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
            } else {
                String errorMsg = "No Authorization Code available.";
                log.error(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
                throw new APIManagementException(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
            }
        } else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(grantType)) {
            // Access token for password code grant type
            accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
            accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
        } else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(grantType)) {
            accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
            accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
        } else if (isMultiEnvironmentOverviewEnabled) {
            // JWT or Custom grant type
            accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
            accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
            accessTokenRequest.setAssertion(assertion);
            // Pass grant type to extend a custom grant instead of JWT grant in the future
            accessTokenRequest.setGrantType(KeyManagerConstants.JWT_GRANT_TYPE);
            accessTokenRequest.setScopes(scopes);
            accessTokenRequest.setValidityPeriod(validityPeriod);
            accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
            String usernameFromJWT = getUsernameFromJWT(accessTokenInfo.getIdToken());
            try {
                identityProvider.getIdOfUser(usernameFromJWT);
            } catch (IdentityProviderException e) {
                String errorMsg = "User " + usernameFromJWT + " does not exists in this environment.";
                throw new APIManagementException(errorMsg, e, ExceptionCodes.USER_NOT_AUTHENTICATED);
            }
        }
    } catch (KeyManagementException e) {
        String errorMsg = "Error while receiving tokens for OAuth application : " + appName;
        log.error(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
    log.debug("Received access token for {} application.", appName);
    return accessTokenInfo;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 2 with MultiEnvironmentOverview

use of org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetAuthenticationConfigurations.

@Test
public void testGetAuthenticationConfigurations() throws Exception {
    // Happy Path - 200
    // // Mocked response object from DCR api
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    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);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setCallBackURL("https://localhost/9292/login/callback/store");
    // // Expected data object to be passed to the front-end
    JsonObject oAuthData = new JsonObject();
    String scopes = "apim:self-signup apim:dedicated_gateway apim:subscribe openid";
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationInfo.getClientId());
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationInfo.getCallBackURL());
    oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
    oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, "https://localhost:9080/oauth2/authorize");
    oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, ServiceReferenceHolder.getInstance().getAPIMAppConfiguration().isSsoEnabled());
    oAuthData.addProperty(AuthenticatorConstants.MULTI_ENVIRONMENT_OVERVIEW_ENABLED, APIMConfigurationService.getInstance().getEnvironmentConfigurations().getMultiEnvironmentOverview().isEnabled());
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Get data object to be passed to the front-end
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    JsonObject responseOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseOAuthDataObj, oAuthData);
    // Error Path - 500 - When OAuthApplicationInfo is null
    JsonObject emptyOAuthDataObj = new JsonObject();
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(null);
    JsonObject responseEmptyOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseEmptyOAuthDataObj, emptyOAuthDataObj);
    // Error Path - When DCR application creation fails and throws an APIManagementException
    Mockito.when(keyManager.createApplication(Mockito.any())).thenThrow(KeyManagementException.class);
    try {
        authenticatorService.getAuthenticationConfigurations("store");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while creating the keys for OAuth application : store");
    }
}
Also used : 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) JsonObject(com.google.gson.JsonObject) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) 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)

Example 3 with MultiEnvironmentOverview

use of org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetAuthenticationConfigurationsForPublisher.

@Test
public void testGetAuthenticationConfigurationsForPublisher() throws Exception {
    // Happy Path - 200
    // // Mocked response object from DCR api
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    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);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setCallBackURL("https://localhost:9292/login/callback/publisher");
    // // Expected data object to be passed to the front-end
    JsonObject oAuthData = new JsonObject();
    String scopes = "apim:api_view apim:api_create apim:api_update apim:api_delete apim:apidef_update " + "apim:api_publish apim:subscription_view apim:subscription_block openid " + "apim:external_services_discover apim:dedicated_gateway";
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationInfo.getClientId());
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationInfo.getCallBackURL());
    oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
    oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, "https://localhost:9443/oauth2/authorize");
    oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, ServiceReferenceHolder.getInstance().getAPIMAppConfiguration().isSsoEnabled());
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    multiEnvironmentOverview.setEnabled(true);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Get data object to be passed to the front-end
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    JsonObject responseOAuthDataObj = authenticatorService.getAuthenticationConfigurations("publisher");
    String[] scopesActual = responseOAuthDataObj.get(KeyManagerConstants.TOKEN_SCOPES).toString().split(" ");
    String[] scopesExpected = oAuthData.get(KeyManagerConstants.TOKEN_SCOPES).toString().split(" ");
    Assert.assertEquals(scopesActual.length, scopesExpected.length);
    // Error Path - 500 - When OAuthApplicationInfo is null
    JsonObject emptyOAuthDataObj = new JsonObject();
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(null);
    JsonObject responseEmptyOAuthDataObj = authenticatorService.getAuthenticationConfigurations("publisher");
    Assert.assertEquals(responseEmptyOAuthDataObj, emptyOAuthDataObj);
    // Error Path - When DCR application creation fails and throws an APIManagementException
    Mockito.when(keyManager.createApplication(Mockito.any())).thenThrow(KeyManagementException.class);
    try {
        authenticatorService.getAuthenticationConfigurations("publisher");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while creating the keys for OAuth application : publisher");
    }
}
Also used : JsonObject(com.google.gson.JsonObject) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) 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)

Example 4 with MultiEnvironmentOverview

use of org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview 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)

Example 5 with MultiEnvironmentOverview

use of org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testSetAccessTokenData.

@Test
public void testSetAccessTokenData() throws Exception {
    // Happy Path
    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);
    // // AccessTokenInfo object
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    accessTokenInfo.setIdToken("eyJ4NXQiOiJObUptT0dVeE16WmxZak0yWkRSaE5UWmxZVEExWXpkaFpUUmlPV0UwTldJMk0ySm1PVGMxWkEiLCJraWQiOiJkMGVjNTE0YTMyYjZmODhjMGFiZDEyYTI4NDA2OTliZGQzZGViYTlkIiwiYWxnIjoiUlMyNTYifQ.eyJhdF9oYXNoIjoiWGg3bFZpSDZDS2pZLXRIT09JaWN5QSIsInN1YiI6ImFkbWluIiwiYXVkIjpbInR6NlJGQnhzdV93Z0RCd3FyUThvVmo3d25FTWEiXSwiYXpwIjoidHo2UkZCeHN1X3dnREJ3cXJROG9Wajd3bkVNYSIsImF1dGhfdGltZSI6MTUwMTczMzQ1NiwiaXNzIjoiaHR0cHM6XC9cL2xvY2FsaG9zdDo5NDQzXC9vYXV0aDJcL3Rva2VuIiwiZXhwIjoxNTAxNzM3MDU3LCJpYXQiOjE1MDE3MzM0NTd9.XXX-XXX");
    accessTokenInfo.setValidityPeriod(-2L);
    accessTokenInfo.setScopes("apim:subscribe openid");
    // // Expected AuthResponseBean object
    AuthResponseBean expectedAuthResponseBean = new AuthResponseBean();
    expectedAuthResponseBean.setTokenValid(true);
    expectedAuthResponseBean.setAuthUser("admin");
    expectedAuthResponseBean.setScopes(accessTokenInfo.getScopes());
    expectedAuthResponseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
    expectedAuthResponseBean.setValidityPeriod(accessTokenInfo.getValidityPeriod());
    expectedAuthResponseBean.setIdToken(accessTokenInfo.getIdToken());
    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);
    // // Actual response
    AuthResponseBean authResponseBean = authenticatorService.getResponseBeanFromTokenInfo(accessTokenInfo);
    Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedAuthResponseBean, authResponseBean));
    // Happy Path - When id token is null
    // // AccessTokenInfo object with null id token
    AccessTokenInfo invalidTokenInfo = new AccessTokenInfo();
    invalidTokenInfo.setValidityPeriod(-2L);
    invalidTokenInfo.setScopes("apim:subscribe openid");
    // // Expected AuthResponseBean object when id token is null
    AuthResponseBean expectedResponseBean = new AuthResponseBean();
    expectedResponseBean.setTokenValid(true);
    expectedResponseBean.setScopes(invalidTokenInfo.getScopes());
    expectedResponseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
    expectedResponseBean.setValidityPeriod(invalidTokenInfo.getValidityPeriod());
    expectedResponseBean.setIdToken(invalidTokenInfo.getIdToken());
    expectedResponseBean.setAuthUser("admin");
    // // Actual response when id token is null
    AuthResponseBean responseBean = authenticatorService.getResponseBeanFromTokenInfo(invalidTokenInfo);
    Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedResponseBean, responseBean));
    // Error Path - When parsing JWT fails and throws KeyManagementException
    // // AccessTokenInfo object with invalid ID token format
    AccessTokenInfo invalidAccessTokenInfo = new AccessTokenInfo();
    invalidAccessTokenInfo.setIdToken("xxx-invalid-id-token-xxx");
    invalidAccessTokenInfo.setValidityPeriod(-2L);
    invalidAccessTokenInfo.setScopes("apim:subscribe openid");
    try {
        AuthResponseBean errorResponseBean = authenticatorService.getResponseBeanFromTokenInfo(invalidAccessTokenInfo);
    } catch (KeyManagementException e) {
        Assert.assertEquals(900986, e.getErrorHandler().getErrorCode());
    }
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) AuthResponseBean(org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean) Test(org.junit.Test)

Aggregations

MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)6 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)6 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)5 Test (org.junit.Test)4 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)4 APIMConfigurationService (org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService)4 EnvironmentConfigurations (org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations)4 SystemApplicationDao (org.wso2.carbon.apimgt.core.dao.SystemApplicationDao)4 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)4 APIMAppConfigurationService (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService)4 JsonObject (com.google.gson.JsonObject)3 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)3 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)3 ArrayList (java.util.ArrayList)1 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)1 IdentityProviderException (org.wso2.carbon.apimgt.core.exception.IdentityProviderException)1 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)1 AuthResponseBean (org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean)1