Search in sources :

Example 46 with OAuth

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

the class APIStoreImpl method mapApplicationKeys.

@Override
public OAuthApplicationInfo mapApplicationKeys(String applicationId, String keyType, String clientId, String clientSecret) throws APIManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Semi-manual client registering for App: " + applicationId + " and Client ID: " + clientId);
    }
    if (StringUtils.isEmpty(applicationId) || StringUtils.isEmpty(clientId) || StringUtils.isEmpty(clientSecret)) {
        String msg = "One of input values is null or empty. Application Id: " + applicationId + " Client Id: " + clientId + (StringUtils.isEmpty(clientSecret) ? " Client Secret: " + clientSecret : "");
        log.error(msg);
        throw new APIManagementException(msg, ExceptionCodes.OAUTH2_APP_MAP_FAILED);
    }
    // Checking whether given consumer key and secret match with an existing OAuth app.
    // If they does not match, throw an exception.
    OAuthApplicationInfo oAuthApp = getKeyManager().retrieveApplication(clientId);
    if (oAuthApp == null || !clientSecret.equals(oAuthApp.getClientSecret())) {
        String msg = "Unable to find OAuth app. The provided Client Id is invalid. Client Id: " + clientId;
        throw new APIManagementException(msg, ExceptionCodes.OAUTH2_APP_MAP_FAILED);
    }
    try {
        getApplicationDAO().addApplicationKeys(applicationId, keyType, clientId);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while saving key data.";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    log.debug("Application keys are successfully saved in the database");
    List<SubscriptionValidationData> subscriptionValidationData = getApiSubscriptionDAO().getAPISubscriptionsOfAppForValidation(applicationId, keyType);
    if (subscriptionValidationData != null && !subscriptionValidationData.isEmpty()) {
        getApiGateway().addAPISubscription(subscriptionValidationData);
    }
    if (log.isDebugEnabled()) {
        log.debug("Semi-manual client registration was successful for application: " + applicationId + " and Client ID: " + clientId);
    }
    return oAuthApp;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) SubscriptionValidationData(org.wso2.carbon.apimgt.core.models.SubscriptionValidationData)

Example 47 with OAuth

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

the class DefaultKeyManagerImplTestCase method testCreateApplication.

@Test
public void testCreateApplication() 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);
    // happy path - 201
    // //request object to key manager
    List<String> grantTypesList = new ArrayList<>();
    grantTypesList.add("password");
    grantTypesList.add("client-credentials");
    OAuthAppRequest oauthAppRequest = new OAuthAppRequest("app1", "https://sample.callback/url", "PRODUCTION", grantTypesList);
    // //request object to dcr api
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(oauthAppRequest.getClientName() + '_' + oauthAppRequest.getKeyType());
    dcrClientInfo.setGrantTypes(oauthAppRequest.getGrantTypes());
    dcrClientInfo.addCallbackUrl(oauthAppRequest.getCallBackURL());
    /*
        dcrClientInfo.setUserinfoSignedResponseAlg(ServiceReferenceHolder.getInstance().getAPIMConfiguration()
                .getKeyManagerConfigs().getOidcUserinfoJWTSigningAlgo());
*/
    // //mocked response object from dcr api
    DCRClientInfo dcrClientInfoResponse = new DCRClientInfo();
    dcrClientInfoResponse.setClientName(oauthAppRequest.getClientName());
    dcrClientInfoResponse.setGrantTypes(oauthAppRequest.getGrantTypes());
    dcrClientInfoResponse.addCallbackUrl(oauthAppRequest.getCallBackURL());
    /*
        dcrClientInfoResponse.setUserinfoSignedResponseAlg(ServiceReferenceHolder.getInstance().getAPIMConfiguration()
                .getKeyManagerConfigs().getOidcUserinfoJWTSigningAlgo());
*/
    dcrClientInfoResponse.setClientId("xxx-xxx-xxx-xxx");
    dcrClientInfoResponse.setClientSecret("yyy-yyy-yyy-yyy");
    dcrClientInfoResponse.setClientIdIssuedAt("now");
    dcrClientInfoResponse.setClientSecretExpiresAt("future");
    dcrClientInfoResponse.setRegistrationClientUri("https://localhost:9443/oauth/xxx-xxx-xxx-xxx");
    // //expected response object from key manager
    OAuthApplicationInfo oAuthApplicationInfoResponse = new OAuthApplicationInfo();
    oAuthApplicationInfoResponse.setClientName(dcrClientInfoResponse.getClientName());
    oAuthApplicationInfoResponse.setGrantTypes(dcrClientInfoResponse.getGrantTypes());
    oAuthApplicationInfoResponse.setCallBackURL(dcrClientInfoResponse.getRedirectURIs().get(0));
    oAuthApplicationInfoResponse.setClientId(dcrClientInfoResponse.getClientId());
    oAuthApplicationInfoResponse.setClientSecret(dcrClientInfoResponse.getClientSecret());
    Response dcrResponse = Response.builder().status(201).headers(new HashMap<>()).body(new Gson().toJson(dcrClientInfoResponse), feign.Util.UTF_8).build();
    Mockito.when(dcrmServiceStub.registerApplication(dcrClientInfo)).thenReturn(dcrResponse);
    try {
        OAuthApplicationInfo app = kmImpl.createApplication(oauthAppRequest);
        Assert.assertEquals(app, oAuthApplicationInfoResponse);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - 400
    int errorSc = 400;
    String errorMsg = "{\"error\": \"invalid_redirect_uri\", \"error_description\": \"One or more " + "redirect_uri values are invalid\"}";
    Response errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.registerApplication(any(DCRClientInfo.class))).thenReturn(errorResponse);
    try {
        kmImpl.createApplication(oauthAppRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while DCR application creation."));
    }
    // error case - non-400
    errorSc = 500;
    errorMsg = "unknown error occurred";
    errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.registerApplication(any(DCRClientInfo.class))).thenReturn(errorResponse);
    try {
        kmImpl.createApplication(oauthAppRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while DCR application creation."));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) 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) OAuthAppRequest(org.wso2.carbon.apimgt.core.models.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) Test(org.testng.annotations.Test)

Example 48 with OAuth

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

the class DefaultKeyManagerImplTestCase method testUpdateApplication.

@Test
public void testUpdateApplication() 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 - 200
    // //request object to key manager
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientName("app1");
    List<String> grantTypesList = new ArrayList<>();
    grantTypesList.add("password");
    grantTypesList.add("client-credentials");
    oAuthApplicationInfo.setGrantTypes(grantTypesList);
    oAuthApplicationInfo.setCallBackURL("https://sample.callback/url");
    oAuthApplicationInfo.setClientId(consumerKey);
    oAuthApplicationInfo.setClientSecret("yyy-yyy-yyy-yyy");
    // //request object to dcr api
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(oAuthApplicationInfo.getClientName());
    dcrClientInfo.setGrantTypes(oAuthApplicationInfo.getGrantTypes());
    dcrClientInfo.addCallbackUrl(oAuthApplicationInfo.getCallBackURL());
    /*
        dcrClientInfo.setUserinfoSignedResponseAlg(ServiceReferenceHolder.getInstance().getAPIMConfiguration()
                .getKeyManagerConfigs().getOidcUserinfoJWTSigningAlgo());
*/
    dcrClientInfo.setClientId(oAuthApplicationInfo.getClientId());
    dcrClientInfo.setClientSecret(oAuthApplicationInfo.getClientSecret());
    // //mocked response object from dcr api
    DCRClientInfo dcrClientInfoResponse = new DCRClientInfo();
    dcrClientInfoResponse.setClientName(oAuthApplicationInfo.getClientName());
    dcrClientInfoResponse.setGrantTypes(oAuthApplicationInfo.getGrantTypes());
    dcrClientInfoResponse.addCallbackUrl(oAuthApplicationInfo.getCallBackURL());
    dcrClientInfoResponse.setClientId(consumerKey);
    dcrClientInfoResponse.setClientSecret("yyy-yyy-yyy-yyy");
    dcrClientInfoResponse.setClientIdIssuedAt("now");
    dcrClientInfoResponse.setClientSecretExpiresAt("future");
    dcrClientInfoResponse.setRegistrationClientUri("https://localhost:9443/oauth/xxx-xxx-xxx-xxx");
    // //expected response object from key manager
    OAuthApplicationInfo oAuthApplicationInfoResponse = new OAuthApplicationInfo();
    oAuthApplicationInfoResponse.setClientName(dcrClientInfoResponse.getClientName());
    oAuthApplicationInfoResponse.setGrantTypes(dcrClientInfoResponse.getGrantTypes());
    oAuthApplicationInfoResponse.setCallBackURL(dcrClientInfoResponse.getRedirectURIs().get(0));
    oAuthApplicationInfoResponse.setClientId(dcrClientInfoResponse.getClientId());
    oAuthApplicationInfoResponse.setClientSecret(dcrClientInfoResponse.getClientSecret());
    Response dcrResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(dcrClientInfoResponse), feign.Util.UTF_8).build();
    Mockito.when(dcrmServiceStub.updateApplication(dcrClientInfo, consumerKey)).thenReturn(dcrResponse);
    try {
        OAuthApplicationInfo app = kmImpl.updateApplication(oAuthApplicationInfo);
        Assert.assertEquals(app, oAuthApplicationInfoResponse);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - 400
    int errorSc = 400;
    String errorMsg = "{\"error\": \"invalid_redirect_uri\", \"error_description\": \"One or more " + "redirect_uri values are invalid\"}";
    Response errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.updateApplication(dcrClientInfo, consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.updateApplication(oAuthApplicationInfo);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while updating DCR application."));
    }
    // error case - non-400
    errorSc = 500;
    errorMsg = "unknown error occurred";
    errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.updateApplication(dcrClientInfo, consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.updateApplication(oAuthApplicationInfo);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while updating DCR application."));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) 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) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) Test(org.testng.annotations.Test)

Example 49 with OAuth

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

the class DefaultKeyManagerImplTestCase method testRetrieveApplication.

@Test
public void testRetrieveApplication() 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);
    // happy path - 200
    // //mocked response object from dcr api
    DCRClientInfo dcrClientInfoResponse = new DCRClientInfo();
    dcrClientInfoResponse.setClientName("appx");
    List<String> grantTypesList = new ArrayList<>();
    grantTypesList.add("password");
    grantTypesList.add("client-credentials");
    dcrClientInfoResponse.setGrantTypes(grantTypesList);
    dcrClientInfoResponse.addCallbackUrl("https://sample.callback/url");
    dcrClientInfoResponse.setClientId(consumerKey);
    dcrClientInfoResponse.setClientSecret(consumerSecret);
    dcrClientInfoResponse.setClientIdIssuedAt("now");
    dcrClientInfoResponse.setClientSecretExpiresAt("future");
    dcrClientInfoResponse.setRegistrationClientUri("https://localhost:9443/oauth/xxx-xxx-xxx-xxx");
    // //expected response object from key manager
    OAuthApplicationInfo oAuthApplicationInfoResponse = new OAuthApplicationInfo();
    oAuthApplicationInfoResponse.setClientName(dcrClientInfoResponse.getClientName());
    oAuthApplicationInfoResponse.setGrantTypes(dcrClientInfoResponse.getGrantTypes());
    oAuthApplicationInfoResponse.setCallBackURL(dcrClientInfoResponse.getRedirectURIs().get(0));
    oAuthApplicationInfoResponse.setClientId(dcrClientInfoResponse.getClientId());
    oAuthApplicationInfoResponse.setClientSecret(dcrClientInfoResponse.getClientSecret());
    Response appGetResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(dcrClientInfoResponse), feign.Util.UTF_8).build();
    Mockito.when(dcrmServiceStub.getApplication(consumerKey)).thenReturn(appGetResponse);
    try {
        OAuthApplicationInfo app = kmImpl.retrieveApplication(consumerKey);
        Assert.assertEquals(app, oAuthApplicationInfoResponse);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - empty consumer key
    try {
        kmImpl.retrieveApplication("");
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to retrieve OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - empty consumer null
    try {
        kmImpl.retrieveApplication(null);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Unable to retrieve OAuth Application. Consumer Key is null " + "or empty"));
    }
    // error case - backend error
    String errorMsg = "unknown error occurred";
    Response errorResponse = Response.builder().status(500).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.getApplication(consumerKey)).thenReturn(errorResponse);
    try {
        kmImpl.retrieveApplication(consumerKey);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while retrieving DCR application."));
    }
}
Also used : ArrayList(java.util.ArrayList) 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) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) Test(org.testng.annotations.Test)

Example 50 with OAuth

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

the class APIDefinitionFromSwagger20 method addSecuritySchemeToSwaggerDefinition.

private void addSecuritySchemeToSwaggerDefinition(Swagger swagger, API api) {
    KeyMgtConfigurations keyMgtConfigurations = ServiceReferenceHolder.getInstance().getAPIMConfiguration().getKeyManagerConfigs();
    if ((api.getSecurityScheme() & 2) == 2) {
        // apikey
        log.debug("API security scheme : API Key Scheme");
        if (swagger.getSecurityDefinitions() == null || !swagger.getSecurityDefinitions().containsKey(APIMgtConstants.SWAGGER_APIKEY)) {
            swagger.securityDefinition(APIMgtConstants.SWAGGER_APIKEY, new ApiKeyAuthDefinition(APIMgtConstants.SWAGGER_APIKEY, In.HEADER));
        }
    }
    if ((api.getSecurityScheme() & 1) == 1) {
        log.debug("API security Scheme : Oauth");
        OAuth2Definition oAuth2Definition = new OAuth2Definition();
        oAuth2Definition = oAuth2Definition.application(keyMgtConfigurations.getTokenEndpoint());
        oAuth2Definition.setScopes(Collections.emptyMap());
        if (swagger.getSecurityDefinitions() == null || !swagger.getSecurityDefinitions().containsKey(APIMgtConstants.OAUTH2SECURITY)) {
            swagger.securityDefinition(APIMgtConstants.OAUTH2SECURITY, oAuth2Definition);
        }
    }
}
Also used : ApiKeyAuthDefinition(io.swagger.models.auth.ApiKeyAuthDefinition) KeyMgtConfigurations(org.wso2.carbon.apimgt.core.configuration.models.KeyMgtConfigurations) OAuth2Definition(io.swagger.models.auth.OAuth2Definition)

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