Search in sources :

Example 41 with Credentials

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

the class AccessTokenGenerator method generateNewAccessToken.

private AccessTokenInfo generateNewAccessToken(String[] scopes) {
    try {
        String tokenEndpoint;
        int serverPort;
        URL oauthURL;
        if (StringUtils.isNotEmpty(this.tokenEndpoint)) {
            tokenEndpoint = this.tokenEndpoint;
            oauthURL = new URL(tokenEndpoint);
            serverPort = oauthURL.getPort();
        } else {
            oauthURL = new URL(oauthUrl);
            serverPort = oauthURL.getPort();
            tokenEndpoint = oauthUrl.concat("/token");
        }
        String serverProtocol = oauthURL.getProtocol();
        HttpPost request = new HttpPost(tokenEndpoint);
        HttpClient httpClient = APIUtil.getHttpClient(serverPort, serverProtocol);
        byte[] credentials = org.apache.commons.codec.binary.Base64.encodeBase64((consumerKey + ":" + consumerSecret).getBytes(StandardCharsets.UTF_8));
        request.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
        request.setHeader(APIConstants.CONTENT_TYPE_HEADER, APIConstants.CONTENT_TYPE_APPLICATION_FORM);
        List<BasicNameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair(APIConstants.TOKEN_GRANT_TYPE_KEY, APIConstants.GRANT_TYPE_VALUE));
        if (scopes != null && scopes.length > 0) {
            urlParameters.add(new BasicNameValuePair(APIConstants.OAUTH_RESPONSE_TOKEN_SCOPE, String.join(" ", scopes)));
        }
        request.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse httpResponse = httpClient.execute(request);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String payload = EntityUtils.toString(httpResponse.getEntity());
            JSONObject response = new JSONObject(payload);
            String accessToken = (String) response.get(APIConstants.OAUTH_RESPONSE_ACCESSTOKEN);
            int validityPeriod = (Integer) response.get(APIConstants.OAUTH_RESPONSE_EXPIRY_TIME) * 1000;
            long expiryTime = System.currentTimeMillis() + validityPeriod;
            if (log.isDebugEnabled()) {
                log.debug("Successfully received an access token which expires in " + expiryTime);
            }
            AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
            accessTokenInfo.setAccessToken(accessToken);
            accessTokenInfo.setIssuedTime(System.currentTimeMillis());
            accessTokenInfo.setValidityPeriod(validityPeriod);
            return accessTokenInfo;
        } else {
            log.error("Error occurred when generating a new Access token. Server responded with " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        log.error("Error occurred when generating a new Access token", e);
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URL(java.net.URL) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) JSONObject(org.json.JSONObject) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 42 with Credentials

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

the class BasicAuthAuthenticator method authenticate.

/**
 * Authenticates the given request to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param synCtx The message to be authenticated
 * @return an AuthenticationResponse object which contains the authentication status
 */
@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) {
    if (log.isDebugEnabled()) {
        log.info("Basic Authentication initialized");
    }
    openAPI = (OpenAPI) synCtx.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT);
    if (openAPI == null && !APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        log.error("OpenAPI definition is missing in the gateway. Basic authentication cannot be performed.");
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF, "Basic authentication cannot be performed.");
    }
    // Extract basic authorization header while removing it from the authorization header
    String basicAuthHeader = extractBasicAuthHeader(synCtx);
    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);
    // Check for resource level authentication
    String authenticationScheme;
    List<VerbInfoDTO> verbInfoList;
    if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        HashMap<String, Boolean> operationAuthSchemeMappingList = (HashMap<String, Boolean>) synCtx.getProperty(APIConstants.OPERATION_AUTH_SCHEME_MAPPING);
        HashMap<String, String> operationThrottlingMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.OPERATION_THROTTLING_MAPPING);
        String[] operationList = matchingResource.split(",");
        verbInfoList = new ArrayList<>(1);
        authenticationScheme = APIConstants.AUTH_NO_AUTHENTICATION;
        for (String operation : operationList) {
            boolean operationAuthSchemeEnabled = operationAuthSchemeMappingList.get(operation);
            VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
            if (operationAuthSchemeEnabled) {
                verbInfoDTO.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
                authenticationScheme = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
            } else {
                verbInfoDTO.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
            }
            verbInfoDTO.setThrottling(operationThrottlingMappingList.get(operation));
            verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + operation + ":" + httpMethod);
            verbInfoList.add(verbInfoDTO);
        }
    } else {
        authenticationScheme = OpenAPIUtils.getResourceAuthenticationScheme(openAPI, synCtx);
        verbInfoList = new ArrayList<>(1);
        VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
        verbInfoDTO.setAuthType(authenticationScheme);
        verbInfoDTO.setThrottling(OpenAPIUtils.getResourceThrottlingTier(openAPI, synCtx));
        verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + matchingResource + ":" + httpMethod);
        verbInfoList.add(verbInfoDTO);
    }
    String[] credentials;
    try {
        credentials = extractBasicAuthCredentials(basicAuthHeader);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    String username = getEndUserName(credentials[0]);
    String password = credentials[1];
    // If end user tenant domain does not match the API publisher's tenant domain, return error
    if (!MultitenantUtils.getTenantDomain(username).equals(synCtx.getProperty(PUBLISHER_TENANT_DOMAIN))) {
        log.error("Basic Authentication failure: tenant domain mismatch for user :" + username);
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
    }
    BasicAuthValidationInfoDTO basicAuthValidationInfoObj;
    try {
        if (basicAuthCredentialValidator == null) {
            basicAuthCredentialValidator = new BasicAuthCredentialValidator();
        }
        basicAuthValidationInfoObj = basicAuthCredentialValidator.validate(username, password);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    if (!basicAuthValidationInfoObj.isAuthenticated()) {
        log.error("Basic Authentication failure: Username and Password mismatch");
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    } else {
        // username password matches
        if (log.isDebugEnabled()) {
            log.debug("Basic Authentication: Username and Password authenticated");
        }
        // scope validation
        boolean scopesValid = false;
        try {
            scopesValid = basicAuthCredentialValidator.validateScopes(username, openAPI, synCtx, basicAuthValidationInfoObj);
        } catch (APISecurityException ex) {
            return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
        }
        String domainQualifiedUserName = basicAuthValidationInfoObj.getDomainQualifiedUsername();
        if (scopesValid) {
            if (APISecurityUtils.getAuthenticationContext(synCtx) == null) {
                // Create a dummy AuthenticationContext object with hard coded values for
                // Tier and KeyType. This is because we cannot determine the Tier nor Key
                // Type without subscription information..
                AuthenticationContext authContext = new AuthenticationContext();
                authContext.setAuthenticated(true);
                authContext.setTier(APIConstants.UNAUTHENTICATED_TIER);
                authContext.setStopOnQuotaReach(// Since we don't have details on unauthenticated tier we setting stop on quota reach true
                true);
                synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
                // In basic authentication scenario, we will use the username for throttling.
                authContext.setApiKey(domainQualifiedUserName);
                authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
                authContext.setUsername(domainQualifiedUserName);
                authContext.setCallerToken(null);
                authContext.setApplicationName(APIConstants.BASIC_AUTH_APPLICATION_NAME);
                // Set username as application ID in basic auth scenario
                authContext.setApplicationId(domainQualifiedUserName);
                // Set username as application ID in basic auth scenario
                authContext.setApplicationUUID(domainQualifiedUserName);
                // Set application owner in basic auth scenario
                authContext.setSubscriber(APIConstants.BASIC_AUTH_APPLICATION_OWNER);
                authContext.setConsumerKey(null);
                authContext.setApiTier(apiLevelPolicy);
                APISecurityUtils.setAuthenticationContext(synCtx, authContext, null);
            }
            log.debug("Basic Authentication: Scope validation passed");
            return new AuthenticationResponse(true, isMandatory, false, 0, null);
        }
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) HashMap(java.util.HashMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) BasicAuthValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.BasicAuthValidationInfoDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 43 with Credentials

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

the class WSO2APIPublisherTestCase method testPublishToStoreWithNullStoreArguments.

@Test
public void testPublishToStoreWithNullStoreArguments() {
    // Error path - When username or password or endpoint is not defined
    APIStore nullStore = new APIStore();
    nullStore.setDisplayName(storeName);
    try {
        wso2APIPublisher.publishToStore(api, nullStore);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        String msg = "External APIStore endpoint URL or credentials are not defined. " + "Cannot proceed with publishing API to the APIStore - " + nullStore.getDisplayName();
        Assert.assertEquals(msg, e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIStore(org.wso2.carbon.apimgt.api.model.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 44 with Credentials

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

the class OAuthJwtAuthenticatorImpl method validateJWTToken.

/**
 * Validate the JWT token.
 *
 * @param jti           jwtTokenIdentifier
 * @param signedJWTInfo signed jwt info object
 * @return JWTValidationInfo : token validated info
 */
@MethodStats
private JWTValidationInfo validateJWTToken(SignedJWTInfo signedJWTInfo, String jti, String accessToken, String maskedToken, URL basePath) throws APIManagementException {
    JWTValidationInfo jwtValidationInfo;
    String issuer = signedJWTInfo.getJwtClaimsSet().getIssuer();
    if (StringUtils.isNotEmpty(issuer)) {
        // validate Issuer
        List<String> tokenAudiences = signedJWTInfo.getJwtClaimsSet().getAudience();
        if (tokenIssuers != null && tokenIssuers.containsKey(issuer)) {
            // validate audience
            if (audiencesMap != null && audiencesMap.get(basePath.getPath()) != null && tokenAudiences.stream().anyMatch(audiencesMap.get(basePath.getPath())::contains)) {
                if (isRESTApiTokenCacheEnabled) {
                    JWTValidationInfo tempJWTValidationInfo = (JWTValidationInfo) getRESTAPITokenCache().get(jti);
                    if (tempJWTValidationInfo != null) {
                        Boolean isExpired = checkTokenExpiration(new Date(tempJWTValidationInfo.getExpiryTime()));
                        if (isExpired) {
                            tempJWTValidationInfo.setValid(false);
                            getRESTAPITokenCache().remove(jti);
                            getRESTAPIInvalidTokenCache().put(jti, tempJWTValidationInfo);
                            log.error("JWT token validation failed. Reason: Expired Token. " + maskedToken);
                            return tempJWTValidationInfo;
                        }
                        // check accessToken
                        if (!tempJWTValidationInfo.getRawPayload().equals(accessToken)) {
                            tempJWTValidationInfo.setValid(false);
                            getRESTAPITokenCache().remove(jti);
                            getRESTAPIInvalidTokenCache().put(jti, tempJWTValidationInfo);
                            log.error("JWT token validation failed. Reason: Invalid Token. " + maskedToken);
                            return tempJWTValidationInfo;
                        }
                        return tempJWTValidationInfo;
                    } else if (getRESTAPIInvalidTokenCache().get(jti) != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Token retrieved from the invalid token cache. Token: " + maskedToken);
                        }
                        return (JWTValidationInfo) getRESTAPIInvalidTokenCache().get(jti);
                    }
                }
                // info not in cache. validate signature and exp
                JWTValidator jwtValidator = APIMConfigUtil.getJWTValidatorMap().get(issuer);
                jwtValidationInfo = jwtValidator.validateToken(signedJWTInfo);
                if (jwtValidationInfo.isValid()) {
                    // valid token
                    if (isRESTApiTokenCacheEnabled) {
                        getRESTAPITokenCache().put(jti, jwtValidationInfo);
                    }
                } else {
                    // put in invalid cache
                    if (isRESTApiTokenCacheEnabled) {
                        getRESTAPIInvalidTokenCache().put(jti, jwtValidationInfo);
                    }
                    // invalid credentials : 900901 error code
                    log.error("JWT token validation failed. Reason: Invalid Credentials. " + "Make sure you have provided the correct security credentials in the token :" + maskedToken);
                }
            } else {
                if (audiencesMap == null) {
                    log.error("JWT token audience validation failed. Reason: No audiences registered " + "in the server");
                } else if (audiencesMap.get(basePath.getPath()) == null) {
                    log.error("JWT token audience validation failed. Reason: No audiences registered " + "in the server for the base path (" + basePath.getPath() + ")");
                } else {
                    log.error("JWT token audience validation failed. Reason: None of the aud present " + "in the JWT (" + tokenAudiences.toString() + ") matches the intended audience (" + audiencesMap.get(basePath.getPath()).toString() + ") for base path ( " + basePath.getPath() + " ).");
                }
                return null;
            }
        } else {
            // invalid issuer. invalid token
            log.error("JWT token issuer validation failed. Reason: Issuer present in the JWT (" + issuer + ") does not match with the token issuer (" + tokenIssuers.keySet().toString() + ")");
            return null;
        }
    } else {
        log.error("Issuer is not found in the token " + maskedToken);
        return null;
    }
    return jwtValidationInfo;
}
Also used : JWTValidator(org.wso2.carbon.apimgt.impl.jwt.JWTValidator) Date(java.util.Date) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 45 with Credentials

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

the class PolicyRetriever method invokeService.

private CloseableHttpResponse invokeService(String endpoint, String tenantDomain) throws IOException, ThrottlePolicyDeployerException {
    HttpGet method = new HttpGet(endpoint);
    URL url = new URL(endpoint);
    String username = eventHubConfigurationDto.getUsername();
    String password = eventHubConfigurationDto.getPassword();
    byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password).getBytes(APIConstants.DigestAuthConstants.CHARSET));
    int port = url.getPort();
    String protocol = url.getProtocol();
    method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET));
    HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
    try {
        return APIUtil.executeHTTPRequest(method, httpClient);
    } catch (APIManagementException e) {
        throw new ThrottlePolicyDeployerException(e);
    }
}
Also used : ThrottlePolicyDeployerException(org.wso2.carbon.apimgt.throttle.policy.deployer.exception.ThrottlePolicyDeployerException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) URL(java.net.URL)

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