Search in sources :

Example 1 with IdentityApplicationManagementException

use of org.wso2.carbon.identity.application.common.IdentityApplicationManagementException in project carbon-apimgt by wso2.

the class RegistrationServiceImpl method createApplication.

/**
 * Create a new client application
 *
 * @param appRequest OAuthAppRequest object with client's payload content
 * @return created Application
 * @throws APIKeyMgtException if failed to create the a new application
 */
private OAuthApplicationInfo createApplication(String applicationName, OAuthAppRequest appRequest, String grantType) throws APIManagementException {
    String userName;
    OAuthApplicationInfo applicationInfo = appRequest.getOAuthApplicationInfo();
    String appName = applicationInfo.getClientName();
    String userId = (String) applicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
    boolean isTenantFlowStarted = false;
    if (userId == null || userId.isEmpty()) {
        return null;
    }
    userName = MultitenantUtils.getTenantAwareUsername(userId);
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
        }
        // Creating the service provider
        ServiceProvider serviceProvider = new ServiceProvider();
        serviceProvider.setApplicationName(applicationName);
        serviceProvider.setDescription("Service Provider for application " + appName);
        serviceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        ServiceProviderProperty[] serviceProviderProperties = new ServiceProviderProperty[4];
        ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
        serviceProviderProperty.setName(APP_DISPLAY_NAME);
        serviceProviderProperty.setValue(applicationName);
        serviceProviderProperties[0] = serviceProviderProperty;
        ServiceProviderProperty tokenTypeProviderProperty = new ServiceProviderProperty();
        tokenTypeProviderProperty.setName(APIConstants.APP_TOKEN_TYPE);
        tokenTypeProviderProperty.setValue(applicationInfo.getTokenType());
        serviceProviderProperties[1] = tokenTypeProviderProperty;
        ServiceProviderProperty consentProperty = new ServiceProviderProperty();
        consentProperty.setDisplayName(APIConstants.APP_SKIP_CONSENT_DISPLAY);
        consentProperty.setName(APIConstants.APP_SKIP_CONSENT_NAME);
        consentProperty.setValue(APIConstants.APP_SKIP_CONSENT_VALUE);
        serviceProviderProperties[2] = consentProperty;
        ServiceProviderProperty logoutConsentProperty = new ServiceProviderProperty();
        logoutConsentProperty.setDisplayName(APIConstants.APP_SKIP_LOGOUT_CONSENT_DISPLAY);
        logoutConsentProperty.setName(APIConstants.APP_SKIP_LOGOUT_CONSENT_NAME);
        logoutConsentProperty.setValue(APIConstants.APP_SKIP_LOGOUT_CONSENT_VALUE);
        serviceProviderProperties[3] = logoutConsentProperty;
        serviceProvider.setSpProperties(serviceProviderProperties);
        ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
        appMgtService.createApplication(serviceProvider, tenantDomain, userName);
        // Retrieving the created service provider
        ServiceProvider createdServiceProvider = appMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
        if (createdServiceProvider == null) {
            throw new APIManagementException("Error occurred while creating Service Provider " + "Application" + appName);
        }
        // creating the OAuth app
        OAuthConsumerAppDTO createdOauthApp = this.createOAuthApp(applicationName, applicationInfo, grantType, userName);
        // Set the OAuthApp in InboundAuthenticationConfig
        InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
        InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new InboundAuthenticationRequestConfig[1];
        InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
        String oAuthType = APIConstants.SWAGGER_12_OAUTH2;
        inboundAuthenticationRequestConfig.setInboundAuthType(oAuthType);
        inboundAuthenticationRequestConfig.setInboundAuthKey(createdOauthApp.getOauthConsumerKey());
        String oauthConsumerSecret = createdOauthApp.getOauthConsumerSecret();
        if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
            Property property = new Property();
            property.setName(ApplicationConstants.INBOUNT_AUTH_CONSUMER_SECRET);
            property.setValue(oauthConsumerSecret);
            Property[] properties = { property };
            inboundAuthenticationRequestConfig.setProperties(properties);
        }
        inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
        inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs);
        createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
        // Setting the SaasApplication attribute to created service provider
        createdServiceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        createdServiceProvider.setSpProperties(serviceProviderProperties);
        // Updating the service provider with Inbound Authentication Configs and SaasApplication
        appMgtService.updateApplication(createdServiceProvider, tenantDomain, userName);
        Map<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(OAUTH_REDIRECT_URIS, createdOauthApp.getCallbackUrl());
        valueMap.put(OAUTH_CLIENT_NAME, createdOauthApp.getApplicationName());
        valueMap.put(OAUTH_CLIENT_GRANT, createdOauthApp.getGrantTypes());
        return this.fromAppDTOToApplicationInfo(createdOauthApp.getOauthConsumerKey(), applicationName, createdOauthApp.getCallbackUrl(), createdOauthApp.getOauthConsumerSecret(), createdServiceProvider.isSaasApp(), userId, valueMap);
    } catch (IdentityApplicationManagementException e) {
        log.error("Error occurred while creating the client application " + appName, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
        }
    }
    return null;
}
Also used : InboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig) HashMap(java.util.HashMap) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) Property(org.wso2.carbon.identity.application.common.model.Property)

Example 2 with IdentityApplicationManagementException

use of org.wso2.carbon.identity.application.common.IdentityApplicationManagementException 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 3 with IdentityApplicationManagementException

use of org.wso2.carbon.identity.application.common.IdentityApplicationManagementException in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method getAppsAuthorizedByUser.

/**
 * Method to retrieve applications authorized for user
 * @param authenticatedUser authenticated user info
 * @return array of authorized applications
 * @throws IdentityOAuthAdminException exception
 */
private OAuthConsumerAppDTO[] getAppsAuthorizedByUser(AuthenticatedUser authenticatedUser) throws IdentityOAuthAdminException {
    OAuthAppDAO appDAO = new OAuthAppDAO();
    String tenantAwareusername = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String username = UserCoreUtil.addTenantDomainToEntry(tenantAwareusername, tenantDomain);
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    Set<String> clientIds;
    SystemApplicationDTO[] systemApplicationDTOS;
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    Set<String> systemAppClientIds = new HashSet<>();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        } else {
            for (SystemApplicationDTO applicationDTO : systemApplicationDTOS) {
                try {
                    if (ApplicationMgtUtil.isUserAuthorized(applicationDTO.getName(), tenantAwareusername)) {
                        systemAppClientIds.add(applicationDTO.getConsumerKey());
                    }
                } catch (IdentityApplicationManagementException e) {
                    log.error("Error occurred while checking the authorization of the application " + applicationDTO.getName(), e);
                }
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    clientIds = systemAppClientIds;
    Set<OAuthConsumerAppDTO> appDTOs = new HashSet<>();
    for (String clientId : clientIds) {
        Set<AccessTokenDO> accessTokenDOs;
        try {
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(clientId, authenticatedUser, userStoreDomain, true);
        } catch (IdentityOAuth2Exception e) {
            throw handleError("Error occurred while retrieving access tokens issued for " + "Client ID : " + clientId + ", User ID : " + username, e);
        }
        if (!accessTokenDOs.isEmpty()) {
            Set<String> distinctClientUserScopeCombo = new HashSet<>();
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                AccessTokenDO scopedToken;
                String scopeString = OAuth2Util.buildScopeString(accessTokenDO.getScope());
                try {
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(clientId, authenticatedUser, userStoreDomain, scopeString, true);
                    if (scopedToken != null && !distinctClientUserScopeCombo.contains(clientId + ":" + username)) {
                        OAuthAppDO appDO;
                        try {
                            appDO = appDAO.getAppInformation(scopedToken.getConsumerKey());
                            appDTOs.add(buildConsumerAppDTO(appDO));
                            if (log.isDebugEnabled()) {
                                log.debug("Found App: " + appDO.getApplicationName() + " for user: " + username);
                            }
                        } catch (InvalidOAuthClientException e) {
                            String errorMsg = "Invalid Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        } catch (IdentityOAuth2Exception e) {
                            String errorMsg = "Error occurred while retrieving app information " + "for Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        }
                        distinctClientUserScopeCombo.add(clientId + ":" + username);
                    }
                } catch (IdentityOAuth2Exception e) {
                    String errorMsg = "Error occurred while retrieving latest access token issued for Client ID :" + " " + clientId + ", User ID : " + username + " and Scope : " + scopeString;
                    throw handleError(errorMsg, e);
                }
            }
        }
    }
    return appDTOs.toArray(new OAuthConsumerAppDTO[0]);
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Aggregations

IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)2 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)2 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)2 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)2 HashMap (java.util.HashMap)1 POST (javax.ws.rs.POST)1 Response (javax.ws.rs.core.Response)1 APIMgtDAOException (org.wso2.carbon.apimgt.api.APIMgtDAOException)1 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)1 SystemApplicationDAO (org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO)1 SystemApplicationDTO (org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO)1 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)1 FaultResponse (org.wso2.carbon.apimgt.rest.api.dcr.web.dto.FaultResponse)1 InboundAuthenticationConfig (org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig)1 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig)1 Property (org.wso2.carbon.identity.application.common.model.Property)1 ServiceProviderProperty (org.wso2.carbon.identity.application.common.model.ServiceProviderProperty)1 IdentityOAuthAdminException (org.wso2.carbon.identity.oauth.IdentityOAuthAdminException)1