Search in sources :

Example 31 with OAuthApplicationInfo

use of org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo 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 32 with OAuthApplicationInfo

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

the class AuthenticatorService method getAuthenticationConfigurations.

/**
 * This method returns the details of a DCR application.
 *
 * @param appName Name of the application to be created
 * @return oAuthData - A JsonObject with DCR application details, scopes, auth endpoint, and SSO is enabled or not
 * @throws APIManagementException When creating DCR application fails
 */
public JsonObject getAuthenticationConfigurations(String appName) throws APIManagementException {
    JsonObject oAuthData = new JsonObject();
    MultiEnvironmentOverview multiEnvironmentOverviewConfigs = apimConfigurationService.getEnvironmentConfigurations().getMultiEnvironmentOverview();
    boolean isMultiEnvironmentOverviewEnabled = multiEnvironmentOverviewConfigs.isEnabled();
    List<String> grantTypes = new ArrayList<>();
    grantTypes.add(KeyManagerConstants.PASSWORD_GRANT_TYPE);
    grantTypes.add(KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE);
    grantTypes.add(KeyManagerConstants.REFRESH_GRANT_TYPE);
    if (isMultiEnvironmentOverviewEnabled) {
        grantTypes.add(KeyManagerConstants.JWT_GRANT_TYPE);
    }
    APIMAppConfigurations appConfigs = apimAppConfigurationService.getApimAppConfigurations();
    String callBackURL = appConfigs.getApimBaseUrl() + AuthenticatorConstants.AUTHORIZATION_CODE_CALLBACK_URL + appName;
    // Get scopes of the application
    String scopes = getApplicationScopes(appName);
    log.debug("Set scopes for {} application using swagger definition.", appName);
    OAuthApplicationInfo oAuthApplicationInfo;
    try {
        oAuthApplicationInfo = createDCRApplication(appName, callBackURL, grantTypes);
        if (oAuthApplicationInfo != null) {
            log.debug("Created DCR Application successfully for {}.", appName);
            String oAuthApplicationClientId = oAuthApplicationInfo.getClientId();
            String oAuthApplicationCallBackURL = oAuthApplicationInfo.getCallBackURL();
            oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationClientId);
            oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationCallBackURL);
            oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
            oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, appConfigs.getAuthorizationEndpoint());
            oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, appConfigs.isSsoEnabled());
            oAuthData.addProperty(AuthenticatorConstants.MULTI_ENVIRONMENT_OVERVIEW_ENABLED, isMultiEnvironmentOverviewEnabled);
        } else {
            String errorMsg = "No information available in OAuth application.";
            log.error(errorMsg, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        }
    } catch (APIManagementException e) {
        String errorMsg = "Error while creating the keys for OAuth application : " + appName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    return oAuthData;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) ArrayList(java.util.ArrayList) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) JsonObject(com.google.gson.JsonObject) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)30 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 ArrayList (java.util.ArrayList)12 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)10 Test (org.junit.Test)9 ApplicationKeysDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO)9 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 HashMap (java.util.HashMap)7 DCRClientInfo (org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo)6 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)6 Response (feign.Response)5 Map (java.util.Map)5 Response (javax.ws.rs.core.Response)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)5 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)5 ApplicationCreationResponse (org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse)5 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)5 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)5 Request (org.wso2.msf4j.Request)5