Search in sources :

Example 1 with ServiceProvider

use of org.wso2.carbon.identity.application.common.model.ServiceProvider 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 ServiceProvider

use of org.wso2.carbon.identity.application.common.model.ServiceProvider 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 ServiceProvider

use of org.wso2.carbon.identity.application.common.model.ServiceProvider in project siddhi by wso2.

the class WindowDefinitionTestCase method testEventWindow8.

@Test(expectedExceptions = DuplicateDefinitionException.class)
public void testEventWindow8() throws InterruptedException {
    log.info("WindowDefinitionTestCase Test8");
    SiddhiManager siddhiManager = new SiddhiManager();
    String query = "define stream InStream (meta_tenantId int, contextId string, eventId string, eventType " + "string, authenticationSuccess bool, username string, localUsername string, userStoreDomain string, " + "tenantDomain string, remoteIp string, region string, inboundAuthType string, serviceProvider string," + " rememberMeEnabled bool, forceAuthEnabled bool, passiveAuthEnabled bool, rolesCommaSeparated string," + " authenticationStep string, identityProvider string, authStepSuccess bool, stepAuthenticator string," + " isFirstLogin bool, identityProviderType string, _timestamp long);\n" + "define window countWindow (meta_tenantId int, batchEndTime long, timestamp long) externalTimeBatch" + "(batchEndTime, 1 sec, 0, 10 sec, true);\n" + "from InStream\n" + "select meta_tenantId, eventId\n" + "insert into countStream;\n" + "from countStream\n" + "select meta_tenantId, eventId\n" + "insert into countWindow;";
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(query);
    siddhiAppRuntime.shutdown();
}
Also used : SiddhiAppRuntime(org.wso2.siddhi.core.SiddhiAppRuntime) SiddhiManager(org.wso2.siddhi.core.SiddhiManager) Test(org.testng.annotations.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)2 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)2 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)2 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)2 HashMap (java.util.HashMap)1 POST (javax.ws.rs.POST)1 Response (javax.ws.rs.core.Response)1 Test (org.testng.annotations.Test)1 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)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 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)1 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)1 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)1