Search in sources :

Example 1 with OAUTH2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.OAUTH2 in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method updateApplication.

@Override
public OAuthApplicationInfo updateApplication(OAuthApplicationInfo oAuthApplicationInfo) throws KeyManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Updating OAuth2 application with : " + oAuthApplicationInfo.toString());
    }
    String applicationName = oAuthApplicationInfo.getClientName();
    String keyType = (String) oAuthApplicationInfo.getParameter(KeyManagerConstants.APP_KEY_TYPE);
    if (keyType != null) {
        // Derive oauth2 app name based on key type and user input for app name
        applicationName = applicationName + '_' + keyType;
    }
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(applicationName);
    dcrClientInfo.setClientId(oAuthApplicationInfo.getClientId());
    dcrClientInfo.setClientSecret(oAuthApplicationInfo.getClientSecret());
    dcrClientInfo.addCallbackUrl(oAuthApplicationInfo.getCallBackURL());
    dcrClientInfo.setGrantTypes(oAuthApplicationInfo.getGrantTypes());
    Response response = dcrmServiceStub.updateApplication(dcrClientInfo, dcrClientInfo.getClientId());
    if (response == null) {
        throw new KeyManagementException("Error occurred while updating DCR application. Response is null", ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        // 200 - Success
        try {
            OAuthApplicationInfo oAuthApplicationInfoResponse = getOAuthApplicationInfo(response);
            // setting original parameter list
            oAuthApplicationInfoResponse.setParameters(oAuthApplicationInfo.getParameters());
            if (log.isDebugEnabled()) {
                log.debug("OAuth2 application updated: " + oAuthApplicationInfoResponse.toString());
            }
            return oAuthApplicationInfoResponse;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR application update response " + "message.", e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
        }
    } else if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_400_BAD_REQUEST) {
        // 400 - Known Error
        try {
            DCRError error = (DCRError) new GsonDecoder().decode(response, DCRError.class);
            throw new KeyManagementException("Error occurred while updating DCR application. Error: " + error.getError() + ". Error Description: " + error.getErrorDescription() + ". Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR error message.", e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
        }
    } else {
        // Unknown Error
        throw new KeyManagementException("Error occurred while updating DCR application. Error: " + response.body().toString() + " Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) DCRError(org.wso2.carbon.apimgt.core.auth.dto.DCRError) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 2 with OAUTH2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.OAUTH2 in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetAuthenticationConfigurations.

@Test
public void testGetAuthenticationConfigurations() throws Exception {
    // Happy Path - 200
    // // Mocked response object from DCR api
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setCallBackURL("https://localhost/9292/login/callback/store");
    // // Expected data object to be passed to the front-end
    JsonObject oAuthData = new JsonObject();
    String scopes = "apim:self-signup apim:dedicated_gateway apim:subscribe openid";
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationInfo.getClientId());
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationInfo.getCallBackURL());
    oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
    oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, "https://localhost:9080/oauth2/authorize");
    oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, ServiceReferenceHolder.getInstance().getAPIMAppConfiguration().isSsoEnabled());
    oAuthData.addProperty(AuthenticatorConstants.MULTI_ENVIRONMENT_OVERVIEW_ENABLED, APIMConfigurationService.getInstance().getEnvironmentConfigurations().getMultiEnvironmentOverview().isEnabled());
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Get data object to be passed to the front-end
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    JsonObject responseOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseOAuthDataObj, oAuthData);
    // Error Path - 500 - When OAuthApplicationInfo is null
    JsonObject emptyOAuthDataObj = new JsonObject();
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(null);
    JsonObject responseEmptyOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseEmptyOAuthDataObj, emptyOAuthDataObj);
    // Error Path - When DCR application creation fails and throws an APIManagementException
    Mockito.when(keyManager.createApplication(Mockito.any())).thenThrow(KeyManagementException.class);
    try {
        authenticatorService.getAuthenticationConfigurations("store");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while creating the keys for OAuth application : store");
    }
}
Also used : EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) JsonObject(com.google.gson.JsonObject) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Example 3 with OAUTH2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.OAUTH2 in project carbon-apimgt by wso2.

the class PersistenceHelper method getSampleAPIArtifactForTenant.

public static GenericArtifact getSampleAPIArtifactForTenant() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactImpl(new QName("", "PizzaShackAPI", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_endpointSecured", "false");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("URITemplate_authType3", "Application & Application User");
    artifact.setAttribute("overview_wadl", null);
    artifact.setAttribute("URITemplate_authType4", "Application & Application User");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("URITemplate_authType1", "Application & Application User");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("URITemplate_authType2", "Application & Application User");
    artifact.setAttribute("overview_wsdl", null);
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory");
    artifact.setAttribute("URITemplate_authType0", "Application & Application User");
    artifact.setAttribute("overview_keyManagers", "[\"all\"]");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_context", "/t/wso2.com/pizzashack/1.0.0");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_isLatest", "true");
    artifact.setAttribute("overview_outSequence", "log_out_message");
    artifact.setAttribute("overview_provider", "admin-AT-wso2.com");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_thumbnail", "/t/wso2.com/t/wso2.com/registry/resource/_system/governance/apimgt/applicationdata/provider/admin-AT-wso2.com/PizzaShackAPI/1.0.0/icon");
    artifact.setAttribute("overview_contextTemplate", "/t/wso2.com/pizzashack/{version}");
    artifact.setAttribute("overview_description", "This is a simple API for Pizza Shack online pizza delivery store.");
    artifact.setAttribute("overview_technicalOwner", "John Doe");
    artifact.setAttribute("overview_type", "HTTP");
    artifact.setAttribute("overview_technicalOwnerEmail", "architecture@pizzashack.com");
    artifact.setAttribute("URITemplate_httpVerb4", "DELETE");
    artifact.setAttribute("overview_inSequence", "log_in_message");
    artifact.setAttribute("URITemplate_httpVerb2", "GET");
    artifact.setAttribute("URITemplate_httpVerb3", "PUT");
    artifact.setAttribute("URITemplate_httpVerb0", "POST");
    artifact.setAttribute("URITemplate_httpVerb1", "GET");
    artifact.setAttribute("labels_labelName", "gwlable");
    artifact.setAttribute("overview_businessOwner", "Jane Roe");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_endpointConfig", "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}," + "\"endpoint_security\":{\"production\":{\"password\":\"admin\",\"tokenUrl\":null,\"clientId\":null," + "\"clientSecret\":null,\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":\"BASIC\"," + "\"grantType\":null,\"enabled\":true,\"uniqueIdentifier\":null,\"username\":\"admin\"}," + "\"sandbox\":{\"password\":null,\"tokenUrl\":null,\"clientId\":null,\"clientSecret\":null," + "\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":null,\"grantType\":null,\"enabled\":false," + "\"uniqueIdentifier\":null,\"username\":null}},\"production_endpoints\":" + "{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}}");
    artifact.setAttribute("overview_tier", "Bronze||Silver||Gold||Unlimited");
    artifact.setAttribute("overview_sandboxTps", "1000");
    artifact.setAttribute("overview_apiOwner", "admin@wso2.com");
    artifact.setAttribute("overview_businessOwnerEmail", "marketing@pizzashack.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_implementation", "ENDPOINT");
    artifact.setAttribute("overview_deployments", "null");
    artifact.setAttribute("overview_redirectURL", null);
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_name", "PizzaShackAPI");
    artifact.setAttribute("overview_subscriptionAvailability", "current_tenant");
    artifact.setAttribute("overview_productionTps", "1000");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_visibleRoles", "admin,internal/subscriber");
    artifact.setAttribute("overview_testKey", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":true,\"accessControlAllowOrigins\":[\"*\"]," + "\"accessControlAllowCredentials\":false,\"accessControlAllowHeaders\":[\"authorization\"," + "\"Access-Control-Allow-Origin\",\"Content-Type\",\"SOAPAction\",\"apikey\",\"testKey\"]," + "\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_advertiseOnly", "false");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_endpointPpassword", null);
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_endpointAuthDigest", "false");
    artifact.setAttribute("overview_faultSequence", "json_fault");
    artifact.setAttribute("overview_responseCaching", "Enabled");
    artifact.setAttribute("URITemplate_urlPattern4", "/order/{orderId}");
    artifact.setAttribute("overview_isDefaultVersion", "true");
    artifact.setAttribute("URITemplate_urlPattern2", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern3", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern0", "/order");
    artifact.setAttribute("URITemplate_urlPattern1", "/menu");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "true");
    artifact.setAttribute("overview_endpointUsername", null);
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Example 4 with OAUTH2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.OAUTH2 in project carbon-apimgt by wso2.

the class PersistenceHelper method getSampleAPIProductArtifact.

public static GenericArtifact getSampleAPIProductArtifact() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactImpl(new QName("", "APIProductTest", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("overview_name", "APIProductTest");
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory,basic_auth,api_key");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_subscriptionAvailability", "all_tenants");
    artifact.setAttribute("overview_context", "/prodcontext");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_provider", "admin");
    artifact.setAttribute("overview_visibleRoles", "admin");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_contextTemplate", "/prodcontext/{version}");
    artifact.setAttribute("overview_thumbnail", null);
    artifact.setAttribute("overview_description", "sample product");
    artifact.setAttribute("overview_technicalOwner", null);
    artifact.setAttribute("overview_type", "APIProduct");
    artifact.setAttribute("overview_technicalOwnerEmail", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":false," + "\"accessControlAllowOrigins\":[\"*\"],\"accessControlAllowCredentials\":false," + "\"accessControlAllowHeaders\":[\"authorization\",\"Access-Control-Allow-Origin\",\"Content-Type\"," + "\"SOAPAction\",\"apikey\",\"testKey\"],\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\"," + "\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_businessOwner", "productOwner");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_responseCaching", "Disabled");
    artifact.setAttribute("overview_tier", "Bronze||Gold");
    artifact.setAttribute("overview_businessOwnerEmail", "owner@test.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "false");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Example 5 with OAUTH2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.OAUTH2 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

Test (org.testng.annotations.Test)54 ArrayList (java.util.ArrayList)29 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO)28 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)21 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)20 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)19 HashMap (java.util.HashMap)17 HttpResponse (org.apache.http.HttpResponse)13 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig)12 JSONObject (org.json.simple.JSONObject)11 Matchers.anyString (org.mockito.Matchers.anyString)11 BeforeClass (org.testng.annotations.BeforeClass)11 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)11 ServiceProvider (org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider)11 Connection (java.sql.Connection)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 PreparedStatement (java.sql.PreparedStatement)9 ResultSet (java.sql.ResultSet)9 SQLException (java.sql.SQLException)8 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)7