Search in sources :

Example 26 with OAuth

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

the class APIUtil method extractCustomerKeyFromAuthHeader.

public static String extractCustomerKeyFromAuthHeader(Map headersMap) {
    // From 1.0.7 version of this component onwards remove the OAuth authorization header from
    // the message is configurable. So we dont need to remove headers at this point.
    String authHeader = (String) headersMap.get(HttpHeaders.AUTHORIZATION);
    if (authHeader == null) {
        return null;
    }
    if (authHeader.startsWith("OAuth ") || authHeader.startsWith("oauth ")) {
        authHeader = authHeader.substring(authHeader.indexOf("o"));
    }
    String[] headers = authHeader.split(APIConstants.OAUTH_HEADER_SPLITTER);
    for (String header : headers) {
        String[] elements = header.split(APIConstants.CONSUMER_KEY_SEGMENT_DELIMITER);
        if (elements.length > 1) {
            int j = 0;
            boolean isConsumerKeyHeaderAvailable = false;
            for (String element : elements) {
                if (!"".equals(element.trim())) {
                    if (APIConstants.CONSUMER_KEY_SEGMENT.equals(elements[j].trim())) {
                        isConsumerKeyHeaderAvailable = true;
                    } else if (isConsumerKeyHeaderAvailable) {
                        return removeLeadingAndTrailing(elements[j].trim());
                    }
                }
                j++;
            }
        }
    }
    return null;
}
Also used : Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 27 with OAuth

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

the class OAuthAuthenticator method authenticate.

@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) throws APIManagementException {
    boolean isJwtToken = false;
    String accessToken = null;
    String remainingAuthHeader = "";
    boolean defaultVersionInvoked = false;
    Map headers = (Map) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String tenantDomain = GatewayUtils.getTenantDomain();
    keyManagerList = GatewayUtils.getKeyManagers(synCtx);
    if (keyValidator == null) {
        this.keyValidator = new APIKeyValidator();
    }
    if (jwtValidator == null) {
        this.jwtValidator = new JWTValidator(this.keyValidator, tenantDomain);
    }
    config = getApiManagerConfiguration();
    removeOAuthHeadersFromOutMessage = isRemoveOAuthHeadersFromOutMessage();
    securityContextHeader = getSecurityContextHeader();
    if (headers != null) {
        requestOrigin = (String) headers.get("Origin");
        // Extract the access token from auth header
        // From 1.0.7 version of this component onwards remove the OAuth authorization header from
        // the message is configurable. So we dont need to remove headers at this point.
        String authHeader = (String) headers.get(getSecurityHeader());
        if (authHeader == null) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth2 Authentication: Expected authorization header with the name '".concat(getSecurityHeader()).concat("' was not found."));
            }
        } else {
            ArrayList<String> remainingAuthHeaders = new ArrayList<>();
            boolean consumerkeyFound = false;
            String[] splitHeaders = authHeader.split(oauthHeaderSplitter);
            if (splitHeaders != null) {
                for (int i = 0; i < splitHeaders.length; i++) {
                    String[] elements = splitHeaders[i].split(consumerKeySegmentDelimiter);
                    if (elements != null && elements.length > 1) {
                        int j = 0;
                        boolean isConsumerKeyHeaderAvailable = false;
                        for (String element : elements) {
                            if (!"".equals(element.trim())) {
                                if (consumerKeyHeaderSegment.equals(elements[j].trim())) {
                                    isConsumerKeyHeaderAvailable = true;
                                } else if (isConsumerKeyHeaderAvailable) {
                                    accessToken = removeLeadingAndTrailing(elements[j].trim());
                                    consumerkeyFound = true;
                                }
                            }
                            j++;
                        }
                    }
                    if (!consumerkeyFound) {
                        remainingAuthHeaders.add(splitHeaders[i]);
                    } else {
                        consumerkeyFound = false;
                    }
                }
            }
            remainingAuthHeader = String.join(oauthHeaderSplitter, remainingAuthHeaders);
        }
        if (log.isDebugEnabled()) {
            log.debug(accessToken != null ? "Received Token ".concat(accessToken) : "No valid Authorization header found");
        }
        // Check if client invoked the default version API (accessing API without version).
        defaultVersionInvoked = headers.containsKey(defaultAPIHeader);
    }
    if (log.isDebugEnabled()) {
        log.debug("Default Version API invoked");
    }
    if (removeOAuthHeadersFromOutMessage) {
        // Remove authorization headers sent for authentication at the gateway and pass others to the backend
        if (StringUtils.isNotBlank(remainingAuthHeader)) {
            if (log.isDebugEnabled()) {
                log.debug("Removing OAuth key from Authorization header");
            }
            headers.put(getSecurityHeader(), remainingAuthHeader);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Removing Authorization header from headers");
            }
            headers.remove(getSecurityHeader());
        }
    }
    if (removeDefaultAPIHeaderFromOutMessage) {
        headers.remove(defaultAPIHeader);
    }
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    SignedJWTInfo signedJWTInfo = null;
    // If the matching resource does not require authentication
    Timer timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_RESOURCE_AUTH"));
    Timer.Context context = timer.start();
    org.apache.axis2.context.MessageContext axis2MessageCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    org.apache.axis2.context.MessageContext.setCurrentMessageContext(axis2MessageCtx);
    String authenticationScheme;
    try {
        // Initial guess of a JWT token using the presence of a DOT.
        if (StringUtils.isNotEmpty(accessToken) && accessToken.contains(APIConstants.DOT)) {
            try {
                if (StringUtils.countMatches(accessToken, APIConstants.DOT) != 2) {
                    log.debug("Invalid JWT token. The expected token format is <header.payload.signature>");
                    throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
                }
                signedJWTInfo = getSignedJwt(accessToken);
                if (GatewayUtils.isInternalKey(signedJWTInfo.getJwtClaimsSet()) || GatewayUtils.isAPIKey(signedJWTInfo.getJwtClaimsSet())) {
                    log.debug("Invalid Token Provided");
                    return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
                }
                String keyManager = ServiceReferenceHolder.getInstance().getJwtValidationService().getKeyManagerNameIfJwtValidatorExist(signedJWTInfo);
                if (StringUtils.isNotEmpty(keyManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("KeyManager " + keyManager + "found for authenticate token " + GatewayUtils.getMaskedToken(accessToken));
                    }
                    if (keyManagerList.contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || keyManagerList.contains(keyManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Elected KeyManager " + keyManager + "found in API level list " + String.join(",", keyManagerList));
                        }
                        isJwtToken = true;
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Elected KeyManager " + keyManager + " not found in API level list " + String.join(",", keyManagerList));
                        }
                        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("KeyManager not found for accessToken " + GatewayUtils.getMaskedToken(accessToken));
                    }
                }
            } catch (ParseException | IllegalArgumentException e) {
                log.debug("Not a JWT token. Failed to decode the token header.", e);
            } catch (APIManagementException e) {
                log.error("error while check validation of JWt", e);
                return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
            }
        }
        authenticationScheme = getAPIKeyValidator().getResourceAuthenticationScheme(synCtx);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    context.stop();
    APIKeyValidationInfoDTO info;
    if (APIConstants.NO_MATCHING_AUTH_SCHEME.equals(authenticationScheme)) {
        info = new APIKeyValidationInfoDTO();
        info.setAuthorized(false);
        info.setValidationStatus(900906);
    } else if (accessToken == null || apiContext == null || apiVersion == null) {
        if (log.isDebugEnabled()) {
            if (accessToken == null) {
                log.debug("OAuth headers not found");
            } else if (apiContext == null) {
                log.debug("Couldn't find API Context");
            } else {
                log.debug("Could not find api version");
            }
        }
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_CREDENTIALS, "Required OAuth credentials not provided");
    } else {
        // Start JWT token validation
        if (isJwtToken) {
            try {
                AuthenticationContext authenticationContext = jwtValidator.authenticate(signedJWTInfo, synCtx);
                APISecurityUtils.setAuthenticationContext(synCtx, authenticationContext, securityContextHeader);
                log.debug("User is authorized using JWT token to access the resource.");
                synCtx.setProperty(APIMgtGatewayConstants.END_USER_NAME, authenticationContext.getUsername());
                return new AuthenticationResponse(true, isMandatory, false, 0, null);
            } catch (APISecurityException ex) {
                return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Matching resource is: ".concat(matchingResource));
        }
        timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_KEY_VALIDATION_INFO"));
        context = timer.start();
        try {
            info = getAPIKeyValidator().getKeyValidationInfo(apiContext, accessToken, apiVersion, authenticationScheme, matchingResource, httpMethod, defaultVersionInvoked, keyManagerList);
        } catch (APISecurityException ex) {
            return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
        }
        context.stop();
        synCtx.setProperty(APIMgtGatewayConstants.APPLICATION_NAME, info.getApplicationName());
        synCtx.setProperty(APIMgtGatewayConstants.END_USER_NAME, info.getEndUserName());
        synCtx.setProperty(APIMgtGatewayConstants.SCOPES, info.getScopes() == null ? null : info.getScopes().toString());
    }
    if (info.isAuthorized()) {
        AuthenticationContext authContext = new AuthenticationContext();
        authContext.setAuthenticated(true);
        authContext.setTier(info.getTier());
        authContext.setApiKey(accessToken);
        authContext.setKeyType(info.getType());
        if (info.getEndUserName() != null) {
            authContext.setUsername(info.getEndUserName());
        } else {
            authContext.setUsername(APIConstants.END_USER_ANONYMOUS);
        }
        authContext.setCallerToken(info.getEndUserToken());
        authContext.setApplicationId(info.getApplicationId());
        authContext.setApplicationUUID(info.getApplicationUUID());
        authContext.setApplicationName(info.getApplicationName());
        authContext.setApplicationTier(info.getApplicationTier());
        authContext.setSubscriber(info.getSubscriber());
        authContext.setConsumerKey(info.getConsumerKey());
        authContext.setApiTier(info.getApiTier());
        authContext.setThrottlingDataList(info.getThrottlingDataList());
        authContext.setSubscriberTenantDomain(info.getSubscriberTenantDomain());
        authContext.setSpikeArrestLimit(info.getSpikeArrestLimit());
        authContext.setSpikeArrestUnit(info.getSpikeArrestUnit());
        authContext.setStopOnQuotaReach(info.isStopOnQuotaReach());
        authContext.setIsContentAware(info.isContentAware());
        APISecurityUtils.setAuthenticationContext(synCtx, authContext, securityContextHeader);
        if (info.getProductName() != null && info.getProductProvider() != null) {
            authContext.setProductName(info.getProductName());
            authContext.setProductProvider(info.getProductProvider());
        }
        /* Synapse properties required for BAM Mediator*/
        // String tenantDomain = MultitenantUtils.getTenantDomain(info.getApiPublisher());
        synCtx.setProperty("api.ut.apiPublisher", info.getApiPublisher());
        synCtx.setProperty("API_NAME", info.getApiName());
        /* GraphQL Query Analysis Information */
        if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
            synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, info.getGraphQLMaxDepth());
            synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, info.getGraphQLMaxComplexity());
        }
        if (log.isDebugEnabled()) {
            log.debug("User is authorized to access the Resource");
        }
        return new AuthenticationResponse(true, isMandatory, false, 0, null);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("User is NOT authorized to access the Resource");
        }
        return new AuthenticationResponse(false, isMandatory, true, info.getValidationStatus(), "Access failure for API: " + apiContext + ", version: " + apiVersion + " status: (" + info.getValidationStatus() + ") - " + APISecurityConstants.getAuthenticationFailureMessage(info.getValidationStatus()));
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) ArrayList(java.util.ArrayList) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) Timer(org.wso2.carbon.metrics.manager.Timer) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ParseException(java.text.ParseException) JWTValidator(org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) Map(java.util.Map) TreeMap(java.util.TreeMap) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 28 with OAuth

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

the class APIKeyValidator method getKeyValidationInfo.

/**
 * Get the API key validated against the specified API
 *
 * @param context    API context
 * @param apiKey     API key to be validated
 * @param apiVersion API version number
 * @param keyManagers list of key managers to authenticate the API
 * @return An APIKeyValidationInfoDTO object
 * @throws APISecurityException If an error occurs while accessing backend services
 */
public APIKeyValidationInfoDTO getKeyValidationInfo(String context, String apiKey, String apiVersion, String authenticationScheme, String matchingResource, String httpVerb, boolean defaultVersionInvoked, List<String> keyManagers) throws APISecurityException {
    String prefixedVersion = apiVersion;
    // Check if client has invoked the default version API.
    if (defaultVersionInvoked) {
        // Prefix the version so that it looks like _default_1.0 (_default_<version>)).
        // This is so that the Key Validator knows that this request is coming through a default api version
        prefixedVersion = APIConstants.DEFAULT_VERSION_PREFIX + prefixedVersion;
    }
    String cacheKey = APIUtil.getAccessTokenCacheKey(apiKey, context, prefixedVersion, matchingResource, httpVerb, authenticationScheme);
    // If Gateway key caching is enabled.
    if (gatewayKeyCacheEnabled) {
        // Get the access token from the first level cache.
        String cachedToken = (String) getGatewayTokenCache().get(apiKey);
        // If the access token exists in the first level cache.
        if (cachedToken != null) {
            APIKeyValidationInfoDTO info = (APIKeyValidationInfoDTO) getGatewayKeyCache().get(cacheKey);
            if (info != null) {
                if (APIUtil.isAccessTokenExpired(info)) {
                    log.info("Invalid OAuth Token : Access Token " + GatewayUtils.getMaskedToken(apiKey) + " " + "expired.");
                    info.setAuthorized(false);
                    // in cache, if token is expired  remove cache entry.
                    getGatewayKeyCache().remove(cacheKey);
                    // Remove from the first level token cache as well.
                    getGatewayTokenCache().remove(apiKey);
                    // Put into invalid token cache
                    getInvalidTokenCache().put(apiKey, cachedToken);
                }
                return info;
            }
        } else {
            // Check token available in invalidToken Cache
            String revokedCachedToken = (String) getInvalidTokenCache().get(apiKey);
            if (revokedCachedToken != null) {
                // Token is revoked/invalid or expired
                APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
                apiKeyValidationInfoDTO.setAuthorized(false);
                apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
                return apiKeyValidationInfoDTO;
            }
        }
    }
    String tenantDomain = getTenantDomain();
    APIKeyValidationInfoDTO info = doGetKeyValidationInfo(context, prefixedVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, keyManagers);
    if (info != null) {
        if (gatewayKeyCacheEnabled) {
            if (info.getValidationStatus() == APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS) {
                // if Token is not valid token (expired,invalid,revoked) put into invalid token cache
                getInvalidTokenCache().put(apiKey, tenantDomain);
            } else {
                // Add into 1st level cache and Key cache
                getGatewayTokenCache().put(apiKey, tenantDomain);
                getGatewayKeyCache().put(cacheKey, info);
            }
            // If this is NOT a super-tenant API that is being invoked
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                // to remove the entry when the need occurs to clear this particular cache entry.
                try {
                    startTenantFlow();
                    if (info.getValidationStatus() == APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS) {
                        // if Token is not valid token (expired,invalid,revoked) put into invalid token cache in
                        // tenant cache
                        getInvalidTokenCache().put(apiKey, tenantDomain);
                    } else {
                        // add into to tenant token cache
                        getGatewayTokenCache().put(apiKey, tenantDomain);
                    }
                } finally {
                    endTenantFlow();
                }
            }
        }
        return info;
    } else {
        String warnMsg = "API key validation service returns null object";
        log.warn(warnMsg);
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, warnMsg);
    }
}
Also used : APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 29 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth 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 30 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth 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)

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