Search in sources :

Example 6 with OAuthAppRequest

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

the class APIConsumerImpl method updateAuthClient.

/**
 * @param userId Subscriber name.
 * @param application The Application.
 * @param tokenType Token type (PRODUCTION | SANDBOX)
 * @param callbackUrl callback URL
 * @param allowedDomains allowedDomains for token.
 * @param validityTime validity time period.
 * @param tokenScope Scopes for the requested tokens.
 * @param groupingId APIM application id.
 * @param jsonString Callback URL for the Application.
 * @param keyManagerID Key Manager ID of the relevant Key Manager
 * @return
 * @throws APIManagementException
 */
@Override
public OAuthApplicationInfo updateAuthClient(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String groupingId, String jsonString, String keyManagerID) throws APIManagementException {
    boolean tenantFlowStarted = false;
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            tenantFlowStarted = true;
        }
        final String subscriberName = application.getSubscriber().getName();
        boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
        boolean isUserAppOwner;
        if (isCaseInsensitiveComparisons) {
            isUserAppOwner = subscriberName.equalsIgnoreCase(userId);
        } else {
            isUserAppOwner = subscriberName.equals(userId);
        }
        if (!isUserAppOwner) {
            throw new APIManagementException("user: " + userId + ", attempted to update OAuth application " + "owned by: " + subscriberName);
        }
        String keyManagerName;
        KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerID);
        String keyManagerTenant;
        if (keyManagerConfiguration != null) {
            keyManagerName = keyManagerConfiguration.getName();
            keyManagerTenant = keyManagerConfiguration.getOrganization();
        } else {
            // keeping this just in case the name is sent by mistake.
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerID);
            if (keyManagerConfiguration == null) {
                throw new APIManagementException("Key Manager " + keyManagerID + " couldn't found.", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
            } else {
                keyManagerName = keyManagerID;
                keyManagerID = keyManagerConfiguration.getUuid();
                keyManagerTenant = keyManagerConfiguration.getOrganization();
            }
        }
        if (!keyManagerConfiguration.isEnabled()) {
            throw new APIManagementException("Key Manager " + keyManagerName + " not activated in the requested " + "Tenant", ExceptionCodes.KEY_MANAGER_NOT_ENABLED);
        }
        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_SUPPORTED_TOKEN_GENERATION);
        }
        // Create OauthAppRequest object by passing json String.
        OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, application.getTokenType(), keyManagerTenant, keyManagerName);
        oauthAppRequest.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
        String consumerKey = apiMgtDAO.getConsumerKeyByApplicationIdKeyTypeKeyManager(application.getId(), tokenType, keyManagerID);
        oauthAppRequest.getOAuthApplicationInfo().setClientId(consumerKey);
        // get key manager instance.
        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerTenant, keyManagerName);
        if (keyManager == null) {
            throw new APIManagementException("Key Manager " + keyManagerName + " not initialized in the requested" + "Tenant", ExceptionCodes.KEY_MANAGER_INITIALIZATION_FAILED);
        }
        // set application attributes
        oauthAppRequest.getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
        oauthAppRequest.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
        // call update method.
        OAuthApplicationInfo updatedAppInfo = keyManager.updateApplication(oauthAppRequest);
        apiMgtDAO.updateApplicationKeyTypeMetaData(application.getId(), tokenType, keyManagerID, updatedAppInfo);
        JSONObject appLogObject = new JSONObject();
        appLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, updatedAppInfo.getClientName());
        appLogObject.put("Updated Oauth app with Call back URL", callbackUrl);
        appLogObject.put("Updated Oauth app with grant types", jsonString);
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
        return updatedAppInfo;
    } finally {
        if (tenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) 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) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 7 with OAuthAppRequest

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

the class AMDefaultKeyManagerImpl method updateApplication.

@Override
public OAuthApplicationInfo updateApplication(OAuthAppRequest appInfoDTO) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
    String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
    String applicationName = oAuthApplicationInfo.getClientName();
    String oauthClientName = oAuthApplicationInfo.getApplicationUUID();
    String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
    if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
        // Replace the domain name separator with an underscore for secondary user stores
        String domain = UserCoreUtil.extractDomainFromName(userId);
        if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
            userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
        }
        // Construct the application name subsequent to replacing email domain separator
        oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.getTenantAwareUsername(userId)), oauthClientName, keyType);
    } else {
        throw new APIManagementException("Missing required information for OAuth application update.");
    }
    log.debug("Updating OAuth Client with ID : " + oAuthApplicationInfo.getClientId());
    if (log.isDebugEnabled() && oAuthApplicationInfo.getCallBackURL() != null) {
        log.debug("CallBackURL : " + oAuthApplicationInfo.getCallBackURL());
    }
    if (log.isDebugEnabled() && applicationName != null) {
        log.debug("Client Name : " + oauthClientName);
    }
    ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, true);
    ClientInfo createdClient;
    try {
        createdClient = dcrClient.updateApplication(Base64.getUrlEncoder().encodeToString(oAuthApplicationInfo.getClientId().getBytes(StandardCharsets.UTF_8)), request);
        return buildDTOFromClientInfo(createdClient, new OAuthApplicationInfo());
    } catch (KeyManagerClientException e) {
        handleException("Error occurred while updating OAuth Client : ", e);
        return null;
    }
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Example 8 with OAuthAppRequest

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

the class AMDefaultKeyManagerImpl method updateApplicationOwner.

@Override
public OAuthApplicationInfo updateApplicationOwner(OAuthAppRequest appInfoDTO, String owner) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
    log.debug("Updating Application Owner : " + oAuthApplicationInfo.getClientId());
    ClientInfo updatedClient;
    try {
        updatedClient = dcrClient.updateApplicationOwner(owner, Base64.getUrlEncoder().encodeToString(oAuthApplicationInfo.getClientId().getBytes(StandardCharsets.UTF_8)));
        return buildDTOFromClientInfo(updatedClient, new OAuthApplicationInfo());
    } catch (KeyManagerClientException e) {
        handleException("Error occurred while updating OAuth Client : ", e);
        return null;
    }
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Example 9 with OAuthAppRequest

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

the class AMDefaultKeyManagerImpl method createApplication.

@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws APIManagementException {
    // OAuthApplications are created by calling to APIKeyMgtSubscriber Service
    OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo();
    // Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created.
    String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
    if (StringUtils.isEmpty(userId)) {
        throw new APIManagementException("Missing user ID for OAuth application creation.");
    }
    String applicationName = oAuthApplicationInfo.getClientName();
    String oauthClientName = oauthAppRequest.getOAuthApplicationInfo().getApplicationUUID();
    String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
    if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
        String domain = UserCoreUtil.extractDomainFromName(userId);
        if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
            userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
        }
        oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.getTenantAwareUsername(userId)), oauthClientName, keyType);
    } else {
        throw new APIManagementException("Missing required information for OAuth application creation.");
    }
    if (log.isDebugEnabled()) {
        log.debug("Trying to create OAuth application : " + oauthClientName + " for application: " + applicationName + " and key type: " + keyType);
    }
    String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
    String[] tokenScopes = new String[1];
    tokenScopes[0] = tokenScope;
    ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, false);
    ClientInfo createdClient;
    try {
        createdClient = dcrClient.createApplication(request);
        buildDTOFromClientInfo(createdClient, oAuthApplicationInfo);
        oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
        oAuthApplicationInfo.setIsSaasApplication(false);
        return oAuthApplicationInfo;
    } catch (KeyManagerClientException e) {
        handleException("Can not create OAuth application  : " + oauthClientName + " for application: " + applicationName + " and key type: " + keyType, e);
        return null;
    }
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Example 10 with OAuthAppRequest

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

the class AMDefaultKeyManagerImpl method mapOAuthApplication.

/**
 * This method will create a new record at CLIENT_INFO table by given OauthAppRequest.
 *
 * @param appInfoRequest oAuth application properties will contain in this object
 * @return OAuthApplicationInfo with created oAuth application details.
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
@Override
public OAuthApplicationInfo mapOAuthApplication(OAuthAppRequest appInfoRequest) throws APIManagementException {
    // initiate OAuthApplicationInfo
    OAuthApplicationInfo oAuthApplicationInfo = appInfoRequest.getOAuthApplicationInfo();
    String consumerKey = oAuthApplicationInfo.getClientId();
    String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
    String[] tokenScopes = new String[1];
    tokenScopes[0] = tokenScope;
    String clientSecret = (String) oAuthApplicationInfo.getParameter("client_secret");
    // for the first time we set default time period.
    oAuthApplicationInfo.addParameter(ApplicationConstants.VALIDITY_PERIOD, getConfigurationParamValue(APIConstants.IDENTITY_OAUTH2_FIELD_VALIDITY_PERIOD));
    String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
    // check whether given consumer key and secret match or not. If it does not match throw an exception.
    ClientInfo clientInfo;
    try {
        clientInfo = dcrClient.getApplication(Base64.getUrlEncoder().encodeToString(consumerKey.getBytes(StandardCharsets.UTF_8)));
        buildDTOFromClientInfo(clientInfo, oAuthApplicationInfo);
    } catch (KeyManagerClientException e) {
        handleException("Some thing went wrong while getting OAuth application for given consumer key " + oAuthApplicationInfo.getClientId(), e);
    }
    if (!clientSecret.equals(oAuthApplicationInfo.getClientSecret())) {
        throw new APIManagementException("The secret key is wrong for the given consumer key " + consumerKey);
    }
    oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
    oAuthApplicationInfo.setIsSaasApplication(false);
    if (log.isDebugEnabled()) {
        log.debug("Creating semi-manual application for consumer id  :  " + oAuthApplicationInfo.getClientId());
    }
    return oAuthApplicationInfo;
}
Also used : KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ClientInfo(org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)21 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)9 Application (org.wso2.carbon.apimgt.api.model.Application)6 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)6 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)6 ClientInfo (org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo)5 HashMap (java.util.HashMap)4 JSONObject (org.json.simple.JSONObject)4 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)4 KeyManagerClientException (org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException)4 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)3 KeyManagerConfiguration (org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)3 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)3 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)3 Response (feign.Response)2 IOException (java.io.IOException)2