Search in sources :

Example 6 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class AuthenticatorService method createDCRApplication.

/**
 * This method creates a DCR application.
 *
 * @param clientName  Name of the application to be created
 * @param callBackURL Call back URL of the application
 * @param grantTypes  List of grant types of the application
 * @return OAUthApplicationInfo - An object with DCR Application information
 * @throws APIManagementException When creating DCR application fails
 */
private OAuthApplicationInfo createDCRApplication(String clientName, String callBackURL, List<String> grantTypes) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo;
    try {
        // Here the keyType:"Application" will be passed as a default value
        // for the oAuthAppRequest constructor argument.
        // This value is not related to DCR application creation.
        OAuthAppRequest oAuthAppRequest = new OAuthAppRequest(clientName, callBackURL, AuthenticatorConstants.APPLICATION_KEY_TYPE, grantTypes);
        if (systemApplicationDao.isConsumerKeyExistForApplication(clientName)) {
            String consumerKey = systemApplicationDao.getConsumerKeyForApplication(clientName);
            oAuthApplicationInfo = getKeyManager().retrieveApplication(consumerKey);
        } else {
            oAuthApplicationInfo = getKeyManager().createApplication(oAuthAppRequest);
            if (oAuthApplicationInfo != null) {
                systemApplicationDao.addApplicationKey(clientName, oAuthApplicationInfo.getClientId());
            }
        }
    } catch (KeyManagementException | APIMgtDAOException e) {
        String errorMsg = "Error while creating the keys for OAuth application : " + clientName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    return oAuthApplicationInfo;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.core.models.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 7 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth 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 8 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth 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 9 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class AuthenticatorAPI method redirect.

/**
 * This method provides the DCR application information to the SSO-IS login.
 *
 * @param request Request to call the /login api
 * @return Response - Response object with OAuth data
 */
@OPTIONS
@GET
@Path("/login/{appName}")
@Produces(MediaType.APPLICATION_JSON)
public Response redirect(@Context Request request, @PathParam("appName") String appName) {
    try {
        AuthenticatorService authenticatorService = AuthenticatorAPIFactory.getInstance().getService();
        JsonObject oAuthData = authenticatorService.getAuthenticationConfigurations(appName);
        if (oAuthData.size() == 0) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error while creating the OAuth application!").build();
        } else {
            return Response.status(Response.Status.OK).entity(oAuthData).build();
        }
    } catch (APIManagementException e) {
        ErrorDTO errorDTO = AuthUtil.getErrorDTO(e.getErrorHandler(), null);
        log.error(e.getMessage(), e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO) JsonObject(com.google.gson.JsonObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) OPTIONS(javax.ws.rs.OPTIONS)

Example 10 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testDeleteApplication.

@Test
public void testDeleteApplication() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    final String consumerKey = "xxx-xxx-xxx-xxx";
    // happy path - 204
    Response okResponse = Response.builder().status(204).headers(new HashMap<>()).build();
    Mockito.when(dcrmServiceStub.deleteApplication(consumerKey)).thenReturn(okResponse);
    try {
        kmImpl.deleteApplication(consumerKey);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - empty consumer key
    try {
        kmImpl.deleteApplication("");
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to delete OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - empty consumer null
    try {
        kmImpl.deleteApplication(null);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to delete OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - non-204
    String errorMsg = "unknown error occurred";
    Response errorResponse = Response.builder().status(500).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.deleteApplication(consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.deleteApplication(consumerKey);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while deleting DCR application."));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) HashMap(java.util.HashMap) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) 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) Test(org.testng.annotations.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5