Search in sources :

Example 16 with OAuthAppRequest

use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method createApplication.

@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws KeyManagementException {
    log.debug("Creating OAuth2 application:{}", oauthAppRequest.toString());
    String applicationName = oauthAppRequest.getClientName();
    String keyType = oauthAppRequest.getKeyType();
    if (keyType != null) {
        // Derive oauth2 app name based on key type and user input for app name
        applicationName = applicationName + '_' + keyType;
    }
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(applicationName);
    dcrClientInfo.setGrantTypes(oauthAppRequest.getGrantTypes());
    if (StringUtils.isNotEmpty(oauthAppRequest.getCallBackURL())) {
        dcrClientInfo.addCallbackUrl(oauthAppRequest.getCallBackURL());
    }
    Response response = dcrmServiceStub.registerApplication(dcrClientInfo);
    if (response == null) {
        throw new KeyManagementException("Error occurred while DCR application creation. Response is null", ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_201_CREATED) {
        // 201 - Success
        try {
            OAuthApplicationInfo oAuthApplicationInfoResponse = getOAuthApplicationInfo(response);
            // setting original parameter list
            oAuthApplicationInfoResponse.setParameters(oauthAppRequest.getParameters());
            log.debug("OAuth2 application created: {}", oAuthApplicationInfoResponse.toString());
            return oAuthApplicationInfoResponse;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR application creation response " + "message.", e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        }
    } else if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_400_BAD_REQUEST) {
        // 400 - Known Error
        try {
            DCRError error = (DCRError) new GsonDecoder().decode(response, DCRError.class);
            throw new KeyManagementException("Error occurred while DCR application creation. Error: " + error.getError() + ". Error Description: " + error.getErrorDescription() + ". Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR error message.", e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        }
    } else {
        // Unknown Error
        throw new KeyManagementException("Error occurred while DCR application creation. Error: " + response.body().toString() + " Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) DCRError(org.wso2.carbon.apimgt.core.auth.dto.DCRError) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 17 with OAuthAppRequest

use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest 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 18 with OAuthAppRequest

use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.

the class APIStoreImpl method generateApplicationKeys.

@Override
public OAuthApplicationInfo generateApplicationKeys(String applicationId, String keyType, String callbackUrl, List<String> grantTypes) throws APIManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Generating application keys for application: " + applicationId);
    }
    Application application = getApplicationByUuid(applicationId);
    OAuthAppRequest oauthAppRequest = new OAuthAppRequest(application.getName(), callbackUrl, keyType, grantTypes);
    OAuthApplicationInfo oauthAppInfo = getKeyManager().createApplication(oauthAppRequest);
    if (log.isDebugEnabled()) {
        log.debug("Application key generation was successful for application: " + application.getName() + " Client Id: " + oauthAppInfo.getClientId());
    }
    try {
        getApplicationDAO().addApplicationKeys(applicationId, keyType, oauthAppInfo.getClientId());
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while saving key data for application: " + application.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    if (log.isDebugEnabled()) {
        log.debug("Application keys are successfully saved in the database for application: " + application.getName() + " Client Id: " + oauthAppInfo.getClientId());
    }
    List<SubscriptionValidationData> subscriptionValidationData = getApiSubscriptionDAO().getAPISubscriptionsOfAppForValidation(applicationId, keyType);
    if (subscriptionValidationData != null && !subscriptionValidationData.isEmpty()) {
        getApiGateway().addAPISubscription(subscriptionValidationData);
    }
    return oauthAppInfo;
}
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) SubscriptionValidationData(org.wso2.carbon.apimgt.core.models.SubscriptionValidationData) Application(org.wso2.carbon.apimgt.core.models.Application)

Example 19 with OAuthAppRequest

use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.

the class APIConsumerImplTest method testRequestApprovalForApplicationRegistration.

@Test
public void testRequestApprovalForApplicationRegistration() throws APIManagementException, UserStoreException {
    Scope scope1 = new Scope();
    scope1.setName("api_view");
    Scope scope2 = new Scope();
    scope2.setName("api_create");
    Set<Scope> scopes = new HashSet<Scope>();
    scopes.add(scope1);
    scopes.add(scope2);
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn("abc.org");
    KeyManagerConfigurationDTO keyManagerConfigurationsDto = new KeyManagerConfigurationDTO();
    keyManagerConfigurationsDto.setEnabled(true);
    Mockito.when(apiMgtDAO.getKeyManagerConfigurationByName("abc.org", "default")).thenReturn(keyManagerConfigurationsDto);
    Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenThrow(UserStoreException.class).thenReturn(-1234, 1);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO);
    Application app = new Application("app1", new Subscriber("1"));
    app.setGroupId("2");
    app.setUUID(UUID.randomUUID().toString());
    Mockito.when(userStoreManager.getRoleListOfUser(Mockito.anyString())).thenThrow(UserStoreException.class).thenReturn(new String[] { "role1", "role2" });
    Application application = Mockito.mock(Application.class);
    Subscriber subscriber = Mockito.mock(Subscriber.class);
    Mockito.when(subscriber.getName()).thenReturn("1");
    Mockito.when(application.getSubscriber()).thenReturn(subscriber);
    Mockito.when(ApplicationUtils.retrieveApplication(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(application);
    try {
        apiConsumer.requestApprovalForApplicationRegistration("1", app, "access", "identity.com/auth", null, "3600", "api_view", null, "default", null, false);
        Assert.fail("API management exception not thrown for invalid token type");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Invalid Token Type"));
    }
    scope1.setRoles("role1");
    scope2.setRoles("role2");
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    OAuthAppRequest oAuthAppRequest = new OAuthAppRequest();
    oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
    application = new Application("app1", new Subscriber("1"));
    BDDMockito.when(ApplicationUtils.createOauthAppRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(oAuthAppRequest);
    BDDMockito.when(ApplicationUtils.retrieveApplication(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(application);
    Map<String, Object> result = apiConsumer.requestApprovalForApplicationRegistration("1", app, APIConstants.API_KEY_TYPE_PRODUCTION, "identity.com/auth", null, "3600", "api_view", null, "default", null, false);
    Assert.assertEquals(result.size(), 10);
    Assert.assertEquals(result.get("keyState"), "APPROVED");
    result = apiConsumer.requestApprovalForApplicationRegistration("1", app, APIConstants.API_KEY_TYPE_SANDBOX, "", null, "3600", "api_view", null, "default", null, false);
    Assert.assertEquals(result.size(), 10);
    Assert.assertEquals(result.get("keyState"), "APPROVED");
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) Matchers.anyString(org.mockito.Matchers.anyString) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONObject(org.json.simple.JSONObject) Application(org.wso2.carbon.apimgt.api.model.Application) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 20 with OAuthAppRequest

use of org.wso2.carbon.apimgt.api.model.OAuthAppRequest in project carbon-apimgt by wso2.

the class APIConsumerImplTest method testMapExistingOAuthClient.

@Test
public void testMapExistingOAuthClient() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO);
    apiConsumer.tenantDomain = "carbon.super";
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    OAuthAppRequest oAuthAppRequest = new OAuthAppRequest();
    oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
    BDDMockito.when(ApplicationUtils.createOauthAppRequest(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(oAuthAppRequest);
    Mockito.when(apiMgtDAO.isKeyMappingExistsForConsumerKeyOrApplication(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true, false);
    Mockito.when(keyManager.mapOAuthApplication((OAuthAppRequest) Mockito.any())).thenReturn(oAuthApplicationInfo);
    Mockito.doNothing().when(apiMgtDAO).createApplicationKeyTypeMappingForManualClients(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    KeyManagerConfigurationDTO keyManagerConfigurationsDto = new KeyManagerConfigurationDTO();
    keyManagerConfigurationsDto.setUuid(UUID.randomUUID().toString());
    keyManagerConfigurationsDto.setEnabled(true);
    Mockito.when(apiMgtDAO.isKeyManagerConfigurationExistByName("default", "carbon.super")).thenReturn(true);
    Mockito.when(apiMgtDAO.getKeyManagerConfigurationByName("carbon.super", "default")).thenReturn(keyManagerConfigurationsDto);
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
    Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(keyManagerConfiguration);
    BDDMockito.when(ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplicationInfo, null)).thenReturn(accessTokenRequest);
    Mockito.when(keyManager.getNewApplicationAccessToken(accessTokenRequest)).thenReturn(accessTokenInfo);
    try {
        apiConsumer.mapExistingOAuthClient("", "admin", "1", "app1", "refresh", "DEFAULT", "Resident Key Manager", "carbon.super");
        Assert.fail("Exception is not thrown when client id is already mapped to an application");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Key Mappings already exists for application"));
    }
    Assert.assertEquals(8, apiConsumer.mapExistingOAuthClient("", "admin", "1", "app1", "PRODUCTION", "DEFAULT", "Resident Key Manager", "carbon.super").size());
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)21 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)9 Application (org.wso2.carbon.apimgt.api.model.Application)6 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)6 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)6 ClientInfo (org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)5 HashMap (java.util.HashMap)4 JSONObject (org.json.simple.JSONObject)4 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)4 KeyManagerClientException (org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException)4 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)3 KeyManagerConfiguration (org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)3 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)3 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)3 Response (feign.Response)2 IOException (java.io.IOException)2