Search in sources :

Example 6 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class KeyManagerConfigurationDataRetriever method run.

@Override
public void run() {
    APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    if (apiManagerConfiguration != null) {
        EventHubConfigurationDto eventHubConfigurationDto = apiManagerConfiguration.getEventHubConfigurationDto();
        if (eventHubConfigurationDto != null && eventHubConfigurationDto.isEnabled()) {
            try {
                String url = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP).concat("/keymanagers");
                byte[] credentials = Base64.encodeBase64((eventHubConfigurationDto.getUsername() + ":" + eventHubConfigurationDto.getPassword()).getBytes());
                HttpGet method = new HttpGet(url);
                method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
                method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
                URL configUrl = new URL(url);
                int port = configUrl.getPort();
                String protocol = configUrl.getProtocol();
                HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
                HttpResponse httpResponse = null;
                int retryCount = 0;
                boolean retry;
                do {
                    try {
                        httpResponse = httpClient.execute(method);
                        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                            String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                            KeyManagerConfiguration[] keyManagerConfigurations = new Gson().fromJson(responseString, KeyManagerConfiguration[].class);
                            for (KeyManagerConfiguration keyManagerConfiguration : keyManagerConfigurations) {
                                if (keyManagerConfiguration.isEnabled()) {
                                    try {
                                        ServiceReferenceHolder.getInstance().getKeyManagerConfigurationService().addKeyManagerConfiguration(keyManagerConfiguration.getTenantDomain(), keyManagerConfiguration.getName(), keyManagerConfiguration.getType(), keyManagerConfiguration);
                                    } catch (APIManagementException e) {
                                        log.error("Error while configuring Key Manager " + keyManagerConfiguration.getName() + " in tenant " + keyManagerConfiguration.getTenantDomain(), e);
                                    }
                                }
                            }
                            retry = false;
                        } else {
                            retry = true;
                            retryCount++;
                        }
                    } catch (IOException ex) {
                        retryCount++;
                        int maxRetries = 15;
                        if (retryCount < maxRetries) {
                            retry = true;
                            long retryTimeout = (long) Math.min(Math.pow(2, retryCount), 300);
                            log.warn("Failed retrieving Key Manager Configurations from remote " + "endpoint: " + ex.getMessage() + ". Retrying after " + retryTimeout + " seconds...");
                            Thread.sleep(retryTimeout * 1000);
                        } else {
                            throw ex;
                        }
                    }
                } while (retry);
            } catch (InterruptedException | IOException e) {
                log.error("Error while retrieving key manager configurations", e);
            }
        }
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) URL(java.net.URL) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)

Example 7 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowApprovedByAdmin.

@Test
public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setRoles(roleMap);
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
    PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod();
    PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
    Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true);
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true);
    // Set workflow status to be approved
    workflowDTO.setStatus(WorkflowStatus.APPROVED);
    workflowDTO.setTenantDomain(tenantDomain);
    // Set tenant admin credentials
    userRegistrationConfigDTO.setAdminUserName("admin");
    userRegistrationConfigDTO.setAdminPassword("admin");
    // Test failure to complete workflow execution, when error has been occurred while updating user with signup roles
    Mockito.doThrow(UserStoreException.class).when(userStoreManager).updateRoleListOfUser(Mockito.anyString(), Mockito.any(), new String[] { Mockito.anyString() });
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when sign up roles are not existing in user realm
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false);
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when error has been occurred while retrieving signup config
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException("Error occurred while retrieving signup configuration"));
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 8 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials 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 9 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIMappingUtil method handleAWSCredentials.

/**
 * Set AWS Secret Key based on preserveCredentials state
 *
 * @param awsEndpointConfig   Endpoint configuration of the API
 * @param preserveCredentials Condition to preserve credentials
 * @return Updated endpoint config
 */
private static JSONObject handleAWSCredentials(JSONObject awsEndpointConfig, boolean preserveCredentials) {
    if (StringUtils.isNotEmpty((String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY))) {
        if (!preserveCredentials) {
            awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, APIConstants.AWS_SECRET_KEY);
            return awsEndpointConfig;
        } else {
            String secretKey = (String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            // Decrypting the key since CTL project goes between environments which have different encryption keys.
            try {
                CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
                String decryptedSecret = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
                awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, decryptedSecret);
                return awsEndpointConfig;
            } catch (CryptoException | UnsupportedEncodingException e) {
                log.error("Error while decrypting the Amazon key", e);
            }
        }
    }
    return awsEndpointConfig;
}
Also used : CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CryptoException(org.wso2.carbon.core.util.CryptoException)

Example 10 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials 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)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 HttpClient (org.apache.http.client.HttpClient)12 URL (java.net.URL)10 ArrayList (java.util.ArrayList)9 HttpGet (org.apache.http.client.methods.HttpGet)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 HttpResponse (org.apache.http.HttpResponse)8 Gson (com.google.gson.Gson)6 JSONObject (org.json.simple.JSONObject)6 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Test (org.testng.annotations.Test)6 Response (feign.Response)4 WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)4 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)3 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)3 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)3