Search in sources :

Example 31 with OAuthApplicationInfo

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

the class RegistrationServiceImpl method register.

@POST
@Override
public Response register(RegistrationProfile profile) {
    /**
     * sample message to this method
     * {
     * "callbackUrl": "www.google.lk",
     * "clientName": "mdm",
     * "tokenScope": "Production",
     * "owner": "admin",
     * "grantType": "password refresh_token",
     * "saasApp": true
     *}
     */
    Response response;
    String applicationName = null;
    ErrorDTO errorDTO;
    try {
        OAuthAppRequest appRequest = new OAuthAppRequest();
        OAuthApplicationInfo oauthApplicationInfo = new OAuthApplicationInfo();
        OAuthApplicationInfo returnedAPP;
        String loggedInUserTenantDomain;
        String owner = profile.getOwner();
        String authUserName = RestApiCommonUtil.getLoggedInUsername();
        // correct domain
        if (owner != null && authUserName != null) {
            int index = authUserName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
            int ownerIndex = owner.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
            if (index > 0 && ownerIndex < 0) {
                if (!UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(authUserName.substring(0, index)) && owner.equals(authUserName.substring(index + 1))) {
                    if (log.isDebugEnabled()) {
                        log.debug("Update profile user name :" + owner + " with " + authUserName);
                    }
                    owner = authUserName;
                    profile.setOwner(owner);
                }
            }
        }
        // Validates if the application owner and logged in username is same.
        if (authUserName != null && ((authUserName.equals(owner)) || isUserSuperAdmin(authUserName))) {
            if (!isUserAccessAllowed(authUserName)) {
                String errorMsg = "You do not have enough privileges to create an OAuth app";
                log.error("User " + authUserName + " does not have any of subscribe/create/publish privileges " + "to create an OAuth app");
                errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403L, errorMsg);
                response = Response.status(Response.Status.FORBIDDEN).entity(errorDTO).build();
                return response;
            }
            // Getting client credentials from the profile
            String grantTypes = profile.getGrantType();
            oauthApplicationInfo.setClientName(profile.getClientName());
            if (StringUtils.isNotBlank(profile.getCallbackUrl())) {
                oauthApplicationInfo.setCallBackURL(profile.getCallbackUrl());
            } else {
                String[] grantTypeArr = grantTypes.split(" ");
                for (String grantType : grantTypeArr) {
                    if ((grantType.equalsIgnoreCase(ApplicationConstants.AUTHORIZATION_CODE)) || (grantType.equalsIgnoreCase(ApplicationConstants.IMPLICIT_CONST))) {
                        grantTypes = grantTypes.replace(grantType, "");
                    }
                }
            }
            String tokenType = APIConstants.DEFAULT_TOKEN_TYPE;
            String profileTokenType = profile.getTokenType();
            if (StringUtils.isNotEmpty(profileTokenType)) {
                tokenType = profileTokenType;
            }
            oauthApplicationInfo.addParameter(OAUTH_CLIENT_USERNAME, owner);
            oauthApplicationInfo.setClientId("");
            oauthApplicationInfo.setClientSecret("");
            oauthApplicationInfo.setIsSaasApplication(profile.isSaasApp());
            oauthApplicationInfo.setTokenType(tokenType);
            appRequest.setOAuthApplicationInfo(oauthApplicationInfo);
            if (!authUserName.equals(owner)) {
                loggedInUserTenantDomain = MultitenantUtils.getTenantDomain(owner);
            } else {
                loggedInUserTenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
            }
            String userId = (String) oauthApplicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
            String userNameForSP = MultitenantUtils.getTenantAwareUsername(userId);
            // Replace domain separator by "_" if user is coming from a secondary userstore.
            String domain = UserCoreUtil.extractDomainFromName(userNameForSP);
            if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
                userNameForSP = userNameForSP.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
            }
            applicationName = profile.getClientName();
            ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance();
            // Check if the application is already exists
            ServiceProvider appServiceProvider = null;
            try {
                appServiceProvider = applicationManagementService.getApplicationExcludingFileBasedSPs(applicationName, loggedInUserTenantDomain);
            } catch (IdentityApplicationManagementException e) {
                log.error("Error occurred while checking the existence of the application " + applicationName, e);
            }
            // Retrieving the existing application
            if (appServiceProvider != null) {
                returnedAPP = this.getExistingApp(applicationName, appServiceProvider.isSaasApp());
            } else {
                // create a new application if the application doesn't exists.
                returnedAPP = this.createApplication(applicationName, appRequest, grantTypes);
            }
            // ReturnedAPP is null
            if (returnedAPP == null) {
                String errorMsg = "OAuth app '" + profile.getClientName() + "' creation or updating failed." + " Dynamic Client Registration Service not available.";
                log.error(errorMsg);
                errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
                response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("OAuth app " + profile.getClientName() + " creation successful.");
                }
                response = Response.status(Response.Status.OK).entity(returnedAPP).build();
            }
        } else {
            String errorMsg = "Logged in user '" + authUserName + "' and application owner '" + owner + "' should be same.";
            errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg);
            response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMsg = "Error occurred while trying to create the client application " + applicationName;
        log.error(errorMsg, e);
        errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
        response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
    }
    return response;
}
Also used : FaultResponse(org.wso2.carbon.apimgt.rest.api.dcr.web.dto.FaultResponse) Response(javax.ws.rs.core.Response) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) POST(javax.ws.rs.POST)

Example 32 with OAuthApplicationInfo

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

the class RegistrationServiceImpl method fromAppDTOToApplicationInfo.

/**
 * Creating a OAuthApplicationInfo type object to return
 *
 * @param clientId     client id
 * @param clientName   client name
 * @param callbackUrl  callback url
 * @param clientSecret clientSecret
 * @param saasApp      IsSaasApp
 * @param appOwner     AppOwner
 * @param sampleMap    Map
 * @return OAuthApplicationInfo object containing parsed values.
 */
private OAuthApplicationInfo fromAppDTOToApplicationInfo(String clientId, String clientName, String callbackUrl, String clientSecret, boolean saasApp, String appOwner, Map<String, String> sampleMap) {
    OAuthApplicationInfo updatingApp = new OAuthApplicationInfo();
    updatingApp.setClientId(clientId);
    updatingApp.setClientName(clientName);
    updatingApp.setCallBackURL(callbackUrl);
    updatingApp.setClientSecret(clientSecret);
    updatingApp.setIsSaasApplication(saasApp);
    updatingApp.setAppOwner(appOwner);
    Iterator it = sampleMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        updatingApp.addParameter((String) pair.getKey(), pair.getValue());
        it.remove();
    }
    return updatingApp;
}
Also used : OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Iterator(java.util.Iterator) Map(java.util.Map) HashMap(java.util.HashMap)

Example 33 with OAuthApplicationInfo

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

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

use of org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo 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)

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)37 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)30 Test (org.junit.Test)22 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)21 HashMap (java.util.HashMap)19 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)15 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 ArrayList (java.util.ArrayList)13 Map (java.util.Map)13 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)11 Application (org.wso2.carbon.apimgt.api.model.Application)11 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)10 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)10 JsonObject (com.google.gson.JsonObject)9 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)9 ApplicationKeysDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO)9 JSONObject (org.json.simple.JSONObject)8 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)8 Gson (com.google.gson.Gson)7