Search in sources :

Example 76 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class APIConsumerImpl method mapExistingOAuthClient.

/**
 * @param jsonString this string will contain oAuth app details
 * @param userName user name of logged in user.
 * @param clientId this is the consumer key of oAuthApplication
 * @param applicationName this is the APIM appication name.
 * @param keyType
 * @param tokenType this is theApplication Token Type. This can be either default or jwt.
 * @param keyManagerName key Manager name
 * @return
 * @throws APIManagementException
 */
@Override
public Map<String, Object> mapExistingOAuthClient(String jsonString, String userName, String clientId, String applicationName, String keyType, String tokenType, String keyManagerName, String tenantDomain) throws APIManagementException {
    String callBackURL = null;
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantUtils.getTenantDomain(userName);
    }
    String keyManagerId = null;
    KeyManagerConfigurationDTO keyManagerConfiguration = null;
    if (keyManagerName != null) {
        keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfiguration == null) {
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfiguration != null) {
                keyManagerId = keyManagerName;
                keyManagerName = keyManagerConfiguration.getName();
            }
        } else {
            keyManagerId = keyManagerConfiguration.getUuid();
        }
    } else {
        keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
        keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        keyManagerId = keyManagerConfiguration.getUuid();
    }
    if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
        throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
    if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
        throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
    }
    OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(applicationName, clientId, callBackURL, "default", jsonString, tokenType, tenantDomain, keyManagerName);
    // if clientId is null in the argument `ApplicationUtils#createOauthAppRequest` will set it using
    // the props in `jsonString`. Hence we are taking the updated `clientId` here
    clientId = oauthAppRequest.getOAuthApplicationInfo().getClientId();
    KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
    if (keyManager == null) {
        throw new APIManagementException("Key Manager " + keyManagerName + "Couldn't initialized in tenant " + tenantDomain + ".", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
    // Get application ID
    int applicationId = apiMgtDAO.getApplicationId(applicationName, userName);
    // Checking if clientId is mapped with another application.
    if (apiMgtDAO.isKeyMappingExistsForConsumerKeyOrApplication(applicationId, keyManagerName, keyManagerId, keyType, clientId)) {
        throw new APIManagementException("Key Mappings already exists for application " + applicationName + " or consumer key " + clientId, ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
    }
    if (log.isDebugEnabled()) {
        log.debug("Client ID " + clientId + " not mapped previously with another application. No existing " + "key mappings available for application " + applicationName);
    }
    // createApplication on oAuthorization server.
    OAuthApplicationInfo oAuthApplication = isOauthAppValidation() ? keyManager.mapOAuthApplication(oauthAppRequest) : oauthAppRequest.getOAuthApplicationInfo();
    // Do application mapping with consumerKey.
    String keyMappingId = UUID.randomUUID().toString();
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(keyType, applicationId, clientId, keyManagerId, keyMappingId);
    Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
    AccessTokenInfo tokenInfo;
    if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
        AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
        tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
    } else {
        tokenInfo = new AccessTokenInfo();
        tokenInfo.setAccessToken("");
        tokenInfo.setValidityPeriod(0L);
        String[] noScopes = new String[] { "N/A" };
        tokenInfo.setScope(noScopes);
        oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
    }
    Map<String, Object> keyDetails = new HashMap<String, Object>();
    if (tokenInfo != null) {
        keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
        keyDetails.put("accessToken", tokenInfo.getAccessToken());
        keyDetails.put("tokenDetails", tokenInfo.getJSONString());
    }
    keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, oAuthApplication.getClientId());
    keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, oAuthApplication.getParameter("client_secret"));
    keyDetails.put(APIConstants.FrontEndParameterNames.CLIENT_DETAILS, oAuthApplication.getJsonString());
    keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
    keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.MAPPED.name());
    return keyDetails;
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) 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) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 77 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class APIConsumerImpl method requestApprovalForApplicationRegistration.

/**
 * This method specifically implemented for REST API by removing application and data access logic
 * from host object layer. So as per new implementation we need to pass requested scopes to this method
 * as tokenScope. So we will do scope related other logic here in this method.
 * So host object should only pass required 9 parameters.
 */
@Override
public Map<String, Object> requestApprovalForApplicationRegistration(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String jsonString, String keyManagerName, String tenantDomain, boolean isImportMode) throws APIManagementException {
    boolean isTenantFlowStarted = false;
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantUtils.getTenantDomain(userId);
    } else {
        int tenantId = APIUtil.getInternalOrganizationId(tenantDomain);
        // To handle choreo scenario.
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
    }
    String keyManagerId = null;
    if (keyManagerName != null) {
        KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfiguration == null) {
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfiguration != null) {
                keyManagerId = keyManagerName;
                keyManagerName = keyManagerConfiguration.getName();
            }
        } else {
            keyManagerId = keyManagerConfiguration.getUuid();
        }
        if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
        }
        if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
        }
        Object enableOauthAppCreation = keyManagerConfiguration.getProperty(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION);
        if (enableOauthAppCreation != null && !(Boolean) enableOauthAppCreation) {
            if (isImportMode) {
                log.debug("Importing application when KM OAuth App creation is disabled. Trying to map keys");
                // in the `jsonString` and ApplicationUtils#createOauthAppRequest logic handles it.
                return mapExistingOAuthClient(jsonString, userId, null, application.getName(), tokenType, APIConstants.DEFAULT_TOKEN_TYPE, keyManagerName, tenantDomain);
            } else {
                throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
            }
        }
    }
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        // check if there are any existing key mappings set for the application and the key manager.
        if (apiMgtDAO.isKeyMappingExistsForApplication(application.getId(), keyManagerName, keyManagerId, tokenType)) {
            throw new APIManagementException("Key Mappings already exists for application " + application.getName(), ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
        }
        // initiate WorkflowExecutor
        WorkflowExecutor appRegistrationWorkflow = null;
        // initiate ApplicationRegistrationWorkflowDTO
        ApplicationRegistrationWorkflowDTO appRegWFDto = null;
        ApplicationKeysDTO appKeysDto = new ApplicationKeysDTO();
        boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
        boolean isUserAppOwner;
        if (isCaseInsensitiveComparisons) {
            isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(userId);
        } else {
            isUserAppOwner = application.getSubscriber().getName().equals(userId);
        }
        if (!isUserAppOwner) {
            throw new APIManagementException("user: " + application.getSubscriber().getName() + ", " + "attempted to generate tokens for application owned by: " + userId);
        }
        // if its a PRODUCTION application.
        if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
            // initiate workflow type. By default simple work flow will be
            // executed.
            appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
            appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        } else // if it is a sandBox application.
        if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
            // if its a SANDBOX application.
            appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
            appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        } else {
            throw new APIManagementException("Invalid Token Type '" + tokenType + "' requested.");
        }
        // check whether callback url is empty and set null
        if (StringUtils.isBlank(callbackUrl)) {
            callbackUrl = null;
        }
        String applicationTokenType = application.getTokenType();
        if (StringUtils.isEmpty(application.getTokenType())) {
            applicationTokenType = APIConstants.DEFAULT_TOKEN_TYPE;
        }
        // Build key manager instance and create oAuthAppRequest by jsonString.
        OAuthAppRequest request = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, applicationTokenType, tenantDomain, keyManagerName);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.VALIDITY_PERIOD, validityTime);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_CALLBACK_URL, callbackUrl);
        request.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
        // Setting request values in WorkflowDTO - In future we should keep
        // Application/OAuthApplication related
        // information in the respective entities not in the workflowDTO.
        appRegWFDto.setStatus(WorkflowStatus.CREATED);
        appRegWFDto.setCreatedTime(System.currentTimeMillis());
        appRegWFDto.setTenantDomain(tenantDomain);
        appRegWFDto.setTenantId(tenantId);
        appRegWFDto.setExternalWorkflowReference(appRegistrationWorkflow.generateUUID());
        appRegWFDto.setWorkflowReference(appRegWFDto.getExternalWorkflowReference());
        appRegWFDto.setApplication(application);
        appRegWFDto.setKeyManager(keyManagerId);
        request.setMappingId(appRegWFDto.getWorkflowReference());
        if (!application.getSubscriber().getName().equals(userId)) {
            appRegWFDto.setUserName(application.getSubscriber().getName());
        } else {
            appRegWFDto.setUserName(userId);
        }
        appRegWFDto.setCallbackUrl(appRegistrationWorkflow.getCallbackURL());
        appRegWFDto.setAppInfoDTO(request);
        appRegWFDto.setDomainList(allowedDomains);
        appRegWFDto.setKeyDetails(appKeysDto);
        appRegistrationWorkflow.execute(appRegWFDto);
        Map<String, Object> keyDetails = new HashMap<String, Object>();
        keyDetails.put(APIConstants.FrontEndParameterNames.KEY_STATE, appRegWFDto.getStatus().toString());
        OAuthApplicationInfo applicationInfo = appRegWFDto.getApplicationInfo();
        String keyMappingId = apiMgtDAO.getKeyMappingIdFromApplicationIdKeyTypeAndKeyManager(application.getId(), tokenType, keyManagerId);
        keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
        if (applicationInfo != null) {
            keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, applicationInfo.getClientId());
            keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, applicationInfo.getClientSecret());
            keyDetails.put(ApplicationConstants.OAUTH_APP_DETAILS, applicationInfo.getJsonString());
            keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.CREATED.name());
        }
        // There can be instances where generating the Application Token is
        // not required. In those cases,
        // token info will have nothing.
        AccessTokenInfo tokenInfo = appRegWFDto.getAccessTokenInfo();
        if (tokenInfo != null) {
            keyDetails.put("accessToken", tokenInfo.getAccessToken());
            keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
            keyDetails.put("tokenDetails", tokenInfo.getJSONString());
            keyDetails.put("tokenScope", tokenInfo.getScopes());
        }
        JSONObject appLogObject = new JSONObject();
        appLogObject.put("Generated keys for application", application.getName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
        // if its a PRODUCTION application.
        if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
            // get the workflow state once the executor is executed.
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
            // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
            if (wfDTO != null) {
                if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                    ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                    APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
                }
            } else {
                ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
            }
        } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
            // get the workflow state once the executor is executed.
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
            // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
            if (wfDTO != null) {
                if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                    ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                    APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
                }
            } else {
                ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
            }
        }
        return keyDetails;
    } catch (WorkflowException e) {
        log.error("Could not execute Workflow", e);
        throw new APIManagementException(e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) ApplicationRegistrationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) ApplicationKeysDTO(org.wso2.carbon.apimgt.api.model.ApplicationKeysDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) JSONObject(org.json.simple.JSONObject) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)

Example 78 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class APIConsumerImpl method updateApplicationOwner.

public boolean updateApplicationOwner(String userId, String organization, Application application) throws APIManagementException {
    boolean isAppUpdated;
    String consumerKey;
    String oldUserName = application.getSubscriber().getName();
    String oldTenantDomain = MultitenantUtils.getTenantDomain(oldUserName);
    String newTenantDomain = MultitenantUtils.getTenantDomain(userId);
    if (oldTenantDomain.equals(newTenantDomain)) {
        if (!isSubscriberValid(userId)) {
            RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
            try {
                int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(newTenantDomain);
                UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
                if (userStoreManager.isExistingUser(userId)) {
                    if (apiMgtDAO.getSubscriber(userId) == null) {
                        addSubscriber(userId, "");
                    }
                } else {
                    throw new APIManagementException("User " + userId + " doesn't exist in user store");
                }
            } catch (UserStoreException e) {
                throw new APIManagementException("Error while adding user " + userId + " as a subscriber");
            }
        }
        String applicationName = application.getName();
        if (!APIUtil.isApplicationOwnedBySubscriber(userId, applicationName, organization)) {
            for (APIKey apiKey : application.getKeys()) {
                KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, apiKey.getKeyManager());
                /* retrieving OAuth application information for specific consumer key */
                consumerKey = apiKey.getConsumerKey();
                OAuthApplicationInfo oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
                if (oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_NAME) != null) {
                    OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_NAME).toString(), null, oAuthApplicationInfo.getCallBackURL(), null, null, application.getTokenType(), this.tenantDomain, apiKey.getKeyManager());
                    oauthAppRequest.getOAuthApplicationInfo().setAppOwner(userId);
                    oauthAppRequest.getOAuthApplicationInfo().setClientId(consumerKey);
                    /* updating the owner of the OAuth application with userId */
                    OAuthApplicationInfo updatedAppInfo = keyManager.updateApplicationOwner(oauthAppRequest, userId);
                    isAppUpdated = true;
                    audit.info("Successfully updated the owner of application " + application.getName() + " from " + oldUserName + " to " + userId + ".");
                } else {
                    throw new APIManagementException("Unable to retrieve OAuth application information.");
                }
            }
        } else {
            throw new APIManagementException("Unable to update application owner to " + userId + " as this user has an application with the same name. Update owner to another user.");
        }
    } else {
        throw new APIManagementException("Unable to update application owner to " + userId + " as this user does not belong to " + oldTenantDomain + " domain.");
    }
    isAppUpdated = apiMgtDAO.updateApplicationOwner(userId, application);
    return isAppUpdated;
}
Also used : APIKey(org.wso2.carbon.apimgt.api.model.APIKey) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) RealmService(org.wso2.carbon.user.core.service.RealmService) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 79 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class APIManagerConfiguration method setRecommendationConfigurations.

/**
 * To populate recommendation related configurations
 *
 * @param element
 */
private void setRecommendationConfigurations(OMElement element) {
    OMElement recommendationSeverEndpointElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_ENDPOINT));
    if (recommendationSeverEndpointElement != null) {
        recommendationEnvironment = new RecommendationEnvironment();
        String recommendationSeverEndpoint = recommendationSeverEndpointElement.getText();
        recommendationEnvironment.setRecommendationServerURL(recommendationSeverEndpoint);
        OMElement consumerKeyElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_KEY));
        if (consumerKeyElement != null) {
            if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerKey")) {
                recommendationEnvironment.setConsumerKey(secretResolver.resolve("APIManager.Recommendations.ConsumerKey"));
            } else {
                recommendationEnvironment.setConsumerKey(consumerKeyElement.getText());
            }
            OMElement consumerSecretElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_SECRET));
            if (consumerSecretElement != null) {
                if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerSecret")) {
                    recommendationEnvironment.setConsumerSecret(secretResolver.resolve("APIManager.Recommendations.ConsumerSecret"));
                } else {
                    recommendationEnvironment.setConsumerSecret(consumerSecretElement.getText());
                }
                OMElement oauthEndpointElement = element.getFirstChildWithName(new QName(APIConstants.AUTHENTICATION_ENDPOINT));
                String oauthEndpoint = null;
                if (oauthEndpointElement != null) {
                    oauthEndpoint = oauthEndpointElement.getText();
                } else {
                    try {
                        URL endpointURL = new URL(recommendationSeverEndpoint);
                        oauthEndpoint = endpointURL.getProtocol() + "://" + endpointURL.getHost() + ":" + endpointURL.getPort();
                    } catch (MalformedURLException e) {
                        log.error("Error when reading the recommendationServer Endpoint", e);
                    }
                }
                // Oauth URL is set only if both consumer key
                recommendationEnvironment.setOauthURL(oauthEndpoint);
            // and consumer secrets are correctly defined
            }
        }
        OMElement applyForAllTenantsElement = element.getFirstChildWithName(new QName(APIConstants.APPLY_RECOMMENDATIONS_FOR_ALL_APIS));
        if (applyForAllTenantsElement != null) {
            recommendationEnvironment.setApplyForAllTenants(JavaUtils.isTrueExplicitly(applyForAllTenantsElement.getText()));
        } else {
            log.debug("Apply For All Tenants Element is not set. Set to default true");
        }
        OMElement maxRecommendationsElement = element.getFirstChildWithName(new QName(APIConstants.MAX_RECOMMENDATIONS));
        if (maxRecommendationsElement != null) {
            recommendationEnvironment.setMaxRecommendations(Integer.parseInt(maxRecommendationsElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
        OMElement userNameElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_USERNAME));
        if (userNameElement != null) {
            recommendationEnvironment.setUserName(userNameElement.getText());
            log.debug("Basic OAuth used for recommendation server");
        }
        OMElement passwordElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_PASSWORD));
        if (passwordElement != null) {
            if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.password")) {
                recommendationEnvironment.setPassword(secretResolver.resolve("APIManager.Recommendations.password"));
            } else {
                recommendationEnvironment.setPassword(passwordElement.getText());
            }
        }
        OMElement waitDurationElement = element.getFirstChildWithName(new QName(APIConstants.WAIT_DURATION));
        if (waitDurationElement != null) {
            recommendationEnvironment.setWaitDuration(Long.parseLong(waitDurationElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) URL(java.net.URL)

Example 80 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class AMDefaultKeyManagerImpl method createClientInfo.

/**
 * Construct ClientInfo object for application create request
 *
 * @param info            The OAuthApplicationInfo object
 * @param oauthClientName The name of the OAuth application to be created
 * @param isUpdate        To determine whether the ClientInfo object is related to application update call
 * @return constructed ClientInfo object
 * @throws JSONException          for errors in parsing the OAuthApplicationInfo json string
 * @throws APIManagementException if an error occurs while constructing the ClientInfo object
 */
private ClientInfo createClientInfo(OAuthApplicationInfo info, String oauthClientName, boolean isUpdate) throws JSONException, APIManagementException {
    ClientInfo clientInfo = new ClientInfo();
    JSONObject infoJson = new JSONObject(info.getJsonString());
    String applicationOwner = (String) info.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
    if (infoJson.has(ApplicationConstants.OAUTH_CLIENT_GRANT)) {
        // this is done as there are instances where the grant string begins with a comma character.
        String grantString = infoJson.getString(ApplicationConstants.OAUTH_CLIENT_GRANT);
        if (grantString.startsWith(",")) {
            grantString = grantString.substring(1);
        }
        String[] grantTypes = grantString.split(",");
        clientInfo.setGrantTypes(Arrays.asList(grantTypes));
    }
    if (StringUtils.isNotEmpty(info.getCallBackURL())) {
        String callBackURL = info.getCallBackURL();
        String[] callbackURLs = callBackURL.trim().split("\\s*,\\s*");
        clientInfo.setRedirectUris(Arrays.asList(callbackURLs));
    }
    clientInfo.setClientName(oauthClientName);
    // todo: run tests by commenting the type
    if (StringUtils.isEmpty(info.getTokenType())) {
        clientInfo.setTokenType(APIConstants.TOKEN_TYPE_JWT);
    } else {
        clientInfo.setTokenType(info.getTokenType());
    }
    // being exposed in the JWT token.
    if (APIUtil.isCrossTenantSubscriptionsEnabled() && !tenantDomain.equals(MultitenantUtils.getTenantDomain(applicationOwner))) {
        clientInfo.setApplication_owner(APIUtil.retrieveDefaultReservedUsername());
    } else {
        clientInfo.setApplication_owner(MultitenantUtils.getTenantAwareUsername(applicationOwner));
    }
    if (StringUtils.isNotEmpty(info.getClientId())) {
        if (isUpdate) {
            clientInfo.setClientId(info.getClientId());
        } else {
            clientInfo.setPresetClientId(info.getClientId());
        }
    }
    if (StringUtils.isNotEmpty(info.getClientSecret())) {
        if (isUpdate) {
            clientInfo.setClientId(info.getClientSecret());
        } else {
            clientInfo.setPresetClientSecret(info.getClientSecret());
        }
    }
    Object parameter = info.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
    Map<String, Object> additionalProperties = new HashMap<>();
    if (parameter instanceof String) {
        additionalProperties = new Gson().fromJson((String) parameter, Map.class);
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME)) {
        Object expiryTimeObject = additionalProperties.get(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME);
        if (expiryTimeObject instanceof String) {
            if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
                try {
                    long expiry = Long.parseLong((String) expiryTimeObject);
                    if (expiry < 0) {
                        throw new APIManagementException("Invalid application access token expiry time given for " + oauthClientName, ExceptionCodes.INVALID_APPLICATION_PROPERTIES);
                    }
                    clientInfo.setApplicationAccessTokenLifeTime(expiry);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME)) {
        Object expiryTimeObject = additionalProperties.get(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME);
        if (expiryTimeObject instanceof String) {
            if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
                try {
                    long expiry = Long.parseLong((String) expiryTimeObject);
                    if (expiry < 0) {
                        throw new APIManagementException("Invalid user access token expiry time given for " + oauthClientName, ExceptionCodes.INVALID_APPLICATION_PROPERTIES);
                    }
                    clientInfo.setUserAccessTokenLifeTime(expiry);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME)) {
        Object expiryTimeObject = additionalProperties.get(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME);
        if (expiryTimeObject instanceof String) {
            if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
                try {
                    long expiry = Long.parseLong((String) expiryTimeObject);
                    clientInfo.setRefreshTokenLifeTime(expiry);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME)) {
        Object expiryTimeObject = additionalProperties.get(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME);
        if (expiryTimeObject instanceof String) {
            if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
                try {
                    long expiry = Long.parseLong((String) expiryTimeObject);
                    clientInfo.setIdTokenLifeTime(expiry);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.PKCE_MANDATORY)) {
        Object pkceMandatoryValue = additionalProperties.get(APIConstants.KeyManager.PKCE_MANDATORY);
        if (pkceMandatoryValue instanceof String) {
            if (!APIConstants.KeyManager.PKCE_MANDATORY.equals(pkceMandatoryValue)) {
                try {
                    Boolean pkceMandatory = Boolean.parseBoolean((String) pkceMandatoryValue);
                    clientInfo.setPkceMandatory(pkceMandatory);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN)) {
        Object pkceSupportPlainValue = additionalProperties.get(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN);
        if (pkceSupportPlainValue instanceof String) {
            if (!APIConstants.KeyManager.PKCE_SUPPORT_PLAIN.equals(pkceSupportPlainValue)) {
                try {
                    Boolean pkceSupportPlain = Boolean.parseBoolean((String) pkceSupportPlainValue);
                    clientInfo.setPkceSupportPlain(pkceSupportPlain);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    if (additionalProperties.containsKey(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS)) {
        Object bypassClientCredentialsValue = additionalProperties.get(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS);
        if (bypassClientCredentialsValue instanceof String) {
            if (!APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS.equals(bypassClientCredentialsValue)) {
                try {
                    Boolean bypassClientCredentials = Boolean.parseBoolean((String) bypassClientCredentialsValue);
                    clientInfo.setBypassClientCredentials(bypassClientCredentials);
                } catch (NumberFormatException e) {
                // No need to throw as its due to not a number sent.
                }
            }
        }
    }
    // Set the display name of the application. This name would appear in the consent page of the app.
    clientInfo.setApplicationDisplayName(info.getClientName());
    return clientInfo;
}
Also used : HashMap(java.util.HashMap) Gson(com.google.gson.Gson) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5