Search in sources :

Example 1 with IdentityValidationException

use of org.wso2.carbon.identity.base.IdentityValidationException in project identity-inbound-auth-oauth by wso2-extensions.

the class DCRManagementService method createOAuthApplication.

/**
 * @param profile - RegistrationRequestProfile of the OAuth application to be created.
 * @return RegistrationResponseProfile object which holds the necessary data of created OAuth app.
 * @throws DCRException
 * @throws IdentityException
 */
private RegistrationResponseProfile createOAuthApplication(RegistrationRequestProfile profile) throws DCRException {
    // Subscriber's name should be passed as a parameter, since it's under the subscriber
    // the OAuth App is created.
    String owner = profile.getOwner();
    // Replace all unsupported characters
    String ownerName = owner.replaceAll(String.valueOf(DCRConstants.UNSUPPORTED_CHARACTERS_IN_REGISTRY), "_");
    String applicationName = ownerName + "_" + profile.getClientName();
    // Regex validation of the application name.
    if (!DCRMUtils.isRegexValidated(applicationName)) {
        throw new DCRException("The Application name: " + applicationName + " is not valid! It is not adhering to" + " the regex: " + DCRMUtils.getSPValidatorRegex());
    }
    String grantType = StringUtils.join(profile.getGrantTypes(), " ");
    String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
    String userName = MultitenantUtils.getTenantAwareUsername(profile.getOwner());
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(profile.getTenantDomain(), true);
    // Acting as the provided user. When creating Service Provider/OAuth App,
    // username is fetched from CarbonContext
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
    try {
        // Create the Service Provider
        ServiceProvider serviceProvider = new ServiceProvider();
        serviceProvider.setApplicationName(applicationName);
        User user = new User();
        user.setUserName(UserCoreUtil.removeDomainFromName(userName));
        user.setUserStoreDomain(UserCoreUtil.extractDomainFromName(userName));
        user.setTenantDomain(profile.getTenantDomain());
        serviceProvider.setOwner(user);
        serviceProvider.setDescription("Service Provider for application " + applicationName);
        ApplicationManagementService appMgtService = DCRDataHolder.getInstance().getApplicationManagementService();
        ServiceProvider existingServiceProvider = null;
        ServiceProvider createdServiceProvider = null;
        try {
            existingServiceProvider = appMgtService.getServiceProvider(applicationName, profile.getTenantDomain());
            if (existingServiceProvider == null) {
                appMgtService.createApplication(serviceProvider, profile.getTenantDomain(), userName);
                createdServiceProvider = appMgtService.getServiceProvider(applicationName, profile.getTenantDomain());
            } else {
                String errorMessage = "Service Provider with name: " + applicationName + " already registered";
                throw IdentityException.error(DCRException.class, ErrorCodes.META_DATA_VALIDATION_FAILED.toString(), errorMessage);
            }
        } catch (IdentityApplicationManagementException e) {
            String errorMessage = "Error occurred while reading service provider, " + applicationName;
            throw IdentityException.error(DCRException.class, ErrorCodes.BAD_REQUEST.toString(), errorMessage, e);
        }
        if (createdServiceProvider == null) {
            String errorMessage = "Couldn't create Service Provider Application " + applicationName;
            throw IdentityException.error(DCRException.class, ErrorCodes.META_DATA_VALIDATION_FAILED.toString(), errorMessage);
        }
        // Set SaaS app option
        createdServiceProvider.setSaasApp(false);
        // Then Create OAuthApp
        OAuthAdminService oAuthAdminService = new OAuthAdminService();
        OAuthConsumerAppDTO oAuthConsumerApp = new OAuthConsumerAppDTO();
        oAuthConsumerApp.setApplicationName(applicationName);
        // TODO: After implement multi-urls to the oAuth application, we have to change this API call
        if (profile.getRedirectUris().size() == 0 && (profile.getGrantTypes().contains(DCRConstants.GrantTypes.AUTHORIZATION_CODE) || profile.getGrantTypes().contains(DCRConstants.GrantTypes.IMPLICIT))) {
            String errorMessage = "RedirectUris property must have at least one URI value.";
            throw IdentityException.error(DCRException.class, ErrorCodes.META_DATA_VALIDATION_FAILED.toString(), errorMessage);
        } else if (profile.getRedirectUris().size() == 1) {
            String redirectUri = profile.getRedirectUris().get(0);
            try {
                // validate the redirect uri
                IdentityValidationUtil.getValidInputOverWhiteListPatterns(redirectUri, new String[] { IdentityValidationUtil.ValidatorPattern.URL_WITHOUT_FRAGMENT.name() });
                oAuthConsumerApp.setCallbackUrl(redirectUri);
            } catch (IdentityValidationException e) {
                // TODO: need to add error code
                throw IdentityException.error(DCRException.class, "Redirect URI: " + redirectUri + ", is invalid", e);
            }
        } else if (profile.getRedirectUris().size() > 1) {
            oAuthConsumerApp.setCallbackUrl(OAuthConstants.CALLBACK_URL_REGEXP_PREFIX + createRegexPattern(profile.getRedirectUris()));
        }
        oAuthConsumerApp.setGrantTypes(grantType);
        oAuthConsumerApp.setOAuthVersion(OAUTH_VERSION);
        if (log.isDebugEnabled()) {
            log.debug("Creating OAuth App " + applicationName);
        }
        OAuthConsumerAppDTO createdApp;
        try {
            createdApp = oAuthAdminService.registerAndRetrieveOAuthApplicationData(oAuthConsumerApp);
        } catch (IdentityOAuthAdminException e) {
            throw IdentityException.error(DCRException.class, ErrorCodes.META_DATA_VALIDATION_FAILED.toString(), e.getMessage());
        }
        if (log.isDebugEnabled()) {
            log.debug("Created OAuth App " + applicationName);
            log.debug("Retrieved Details for OAuth App " + createdApp.getApplicationName());
        }
        // Set the OAuthApp in InboundAuthenticationConfig
        InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
        List<InboundAuthenticationRequestConfig> inboundAuthenticationRequestConfigs = new ArrayList<>();
        InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
        inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey());
        inboundAuthenticationRequestConfig.setInboundAuthType(AUTH_TYPE_OAUTH_2);
        String oauthConsumerSecret = createdApp.getOauthConsumerSecret();
        if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
            Property property = new Property();
            property.setName(OAUTH_CONSUMER_SECRET);
            property.setValue(oauthConsumerSecret);
            Property[] properties = { property };
            inboundAuthenticationRequestConfig.setProperties(properties);
        }
        inboundAuthenticationRequestConfigs.add(inboundAuthenticationRequestConfig);
        inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs.toArray(new InboundAuthenticationRequestConfig[inboundAuthenticationRequestConfigs.size()]));
        createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
        // Update the Service Provider app to add OAuthApp as an Inbound Authentication Config
        try {
            appMgtService.updateApplication(createdServiceProvider, profile.getTenantDomain(), userName);
        } catch (IdentityApplicationManagementException e) {
            throw IdentityException.error(DCRException.class, ErrorCodes.BAD_REQUEST.toString(), e.getMessage());
        }
        RegistrationResponseProfile registrationResponseProfile = new RegistrationResponseProfile();
        registrationResponseProfile.setClientId(createdApp.getOauthConsumerKey());
        registrationResponseProfile.getRedirectUrls().add(createdApp.getCallbackUrl());
        registrationResponseProfile.setClientSecret(oauthConsumerSecret);
        registrationResponseProfile.setClientName(createdApp.getApplicationName());
        registrationResponseProfile.setClientSecretExpiresAt(DEFAULT_CLIENT_SECRET_EXPIRY_TIME);
        if (StringUtils.isNotBlank(createdApp.getGrantTypes())) {
            String[] split = createdApp.getGrantTypes().split(" ");
            registrationResponseProfile.setGrantTypes(Arrays.asList(split));
        }
        return registrationResponseProfile;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser);
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) User(org.wso2.carbon.identity.application.common.model.User) InboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig) OAuthAdminService(org.wso2.carbon.identity.oauth.OAuthAdminService) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) ArrayList(java.util.ArrayList) RegistrationResponseProfile(org.wso2.carbon.identity.oauth.dcr.model.RegistrationResponseProfile) IdentityValidationException(org.wso2.carbon.identity.base.IdentityValidationException) InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig) DCRException(org.wso2.carbon.identity.oauth.dcr.DCRException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) Property(org.wso2.carbon.identity.application.common.model.Property)

Aggregations

ArrayList (java.util.ArrayList)1 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)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 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)1 User (org.wso2.carbon.identity.application.common.model.User)1 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)1 IdentityValidationException (org.wso2.carbon.identity.base.IdentityValidationException)1 IdentityOAuthAdminException (org.wso2.carbon.identity.oauth.IdentityOAuthAdminException)1 OAuthAdminService (org.wso2.carbon.identity.oauth.OAuthAdminService)1 DCRException (org.wso2.carbon.identity.oauth.dcr.DCRException)1 RegistrationResponseProfile (org.wso2.carbon.identity.oauth.dcr.model.RegistrationResponseProfile)1 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)1