Search in sources :

Example 11 with MethodStats

use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.

the class AbstractOAuthAuthenticator method validateScopes.

/**
 * @param message   CXF message to be validate
 * @param tokenInfo Token information associated with incoming request
 * @return return true if we found matching scope in resource and token information
 * else false(means scope validation failed).
 */
@MethodStats
public boolean validateScopes(Message message, OAuthTokenInfo tokenInfo) {
    String basePath = (String) message.get(Message.BASE_PATH);
    // path is obtained from Message.REQUEST_URI instead of Message.PATH_INFO, as Message.PATH_INFO contains
    // decoded values of request parameters
    String path = (String) message.get(Message.REQUEST_URI);
    String verb = (String) message.get(Message.HTTP_REQUEST_METHOD);
    String resource = path.substring(basePath.length() - 1);
    String[] scopes = tokenInfo.getScopes();
    String version = (String) message.get(RestApiConstants.API_VERSION);
    // get all the URI templates of the REST API from the base path
    Set<URITemplate> uriTemplates = RestApiUtil.getURITemplatesForBasePath(basePath + version);
    if (uriTemplates.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No matching scopes found for request with path: " + basePath + ". Skipping scope validation.");
        }
        return true;
    }
    for (Object template : uriTemplates.toArray()) {
        org.wso2.uri.template.URITemplate templateToValidate = null;
        Map<String, String> var = new HashMap<String, String>();
        // check scopes with what we have
        String templateString = ((URITemplate) template).getUriTemplate();
        try {
            templateToValidate = new org.wso2.uri.template.URITemplate(templateString);
        } catch (URITemplateException e) {
            log.error("Error while creating URI Template object to validate request. Template pattern: " + templateString, e);
        }
        if (templateToValidate != null && templateToValidate.matches(resource, var) && scopes != null && verb != null && verb.equalsIgnoreCase(((URITemplate) template).getHTTPVerb())) {
            for (String scope : scopes) {
                Scope scp = ((URITemplate) template).getScope();
                if (scp != null) {
                    if (scope.equalsIgnoreCase(scp.getKey())) {
                        // we found scopes matches
                        if (log.isDebugEnabled()) {
                            log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scp.getKey() + " for resource path: " + path + " and verb " + verb);
                        }
                        return true;
                    }
                } else if (!((URITemplate) template).retrieveAllScopes().isEmpty()) {
                    List<Scope> scopesList = ((URITemplate) template).retrieveAllScopes();
                    for (Scope scpObj : scopesList) {
                        if (scope.equalsIgnoreCase(scpObj.getKey())) {
                            // we found scopes matches
                            if (log.isDebugEnabled()) {
                                log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scpObj.getKey() + " for resource path: " + path + " and verb " + verb);
                            }
                            return true;
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Scope not defined in swagger for matching resource " + resource + " and verb " + verb + " . So consider as anonymous permission and let request to continue.");
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : HashMap(java.util.HashMap) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) URITemplateException(org.wso2.uri.template.URITemplateException) Scope(org.wso2.carbon.apimgt.api.model.Scope) List(java.util.List) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 12 with MethodStats

use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.

the class OAuthOpaqueAuthenticatorImpl method getTokenMetaData.

@MethodStats
public OAuthTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    OAuthTokenInfo tokenInfo = new OAuthTokenInfo();
    OAuth2TokenValidationRequestDTO requestDTO = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO.OAuth2AccessToken token = requestDTO.new OAuth2AccessToken();
    token.setIdentifier(accessToken);
    token.setTokenType("bearer");
    requestDTO.setAccessToken(token);
    OAuth2TokenValidationRequestDTO.TokenValidationContextParam[] contextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
    requestDTO.setContext(contextParams);
    OAuth2ClientApplicationDTO clientApplicationDTO = findOAuthConsumerIfTokenIsValid(requestDTO);
    OAuth2TokenValidationResponseDTO responseDTO = clientApplicationDTO.getAccessTokenValidationResponse();
    if (!responseDTO.isValid()) {
        tokenInfo.setTokenValid(responseDTO.isValid());
        log.error("Invalid OAuth Token : " + responseDTO.getErrorMsg());
        return tokenInfo;
    }
    tokenInfo.setTokenValid(responseDTO.isValid());
    tokenInfo.setEndUserName(responseDTO.getAuthorizedUser());
    tokenInfo.setConsumerKey(clientApplicationDTO.getConsumerKey());
    // Convert Expiry Time to milliseconds.
    if (responseDTO.getExpiryTime() == Long.MAX_VALUE) {
        tokenInfo.setValidityPeriod(Long.MAX_VALUE);
    } else {
        tokenInfo.setValidityPeriod(responseDTO.getExpiryTime() * 1000L);
    }
    tokenInfo.setIssuedTime(System.currentTimeMillis());
    tokenInfo.setScopes(responseDTO.getScope());
    return tokenInfo;
}
Also used : OAuth2ClientApplicationDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO) OAuthTokenInfo(org.wso2.carbon.apimgt.api.OAuthTokenInfo) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 13 with MethodStats

use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.

the class ValidationInInterceptor method handleMessage.

@MethodStats
public void handleMessage(Message message) {
    final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
    if (operationResource == null) {
        log.info("OperationResourceInfo is not available, skipping validation");
        return;
    }
    final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
    if (classResource == null) {
        log.info("ClassResourceInfo is not available, skipping validation");
        return;
    }
    final ResourceProvider resourceProvider = classResource.getResourceProvider();
    if (resourceProvider == null) {
        log.info("ResourceProvider is not available, skipping validation");
        return;
    }
    final List<Object> arguments = MessageContentsList.getContentsList(message);
    final Method method = operationResource.getAnnotatedMethod();
    final Object instance = resourceProvider.getInstance(message);
    if (method != null && arguments != null) {
        // validate the parameters(arguments) over the invoked method
        validate(method, arguments.toArray(), instance);
        // validate the fields of each argument
        for (Object arg : arguments) {
            if (arg != null)
                validate(arg);
        }
    }
}
Also used : ResourceProvider(org.apache.cxf.jaxrs.lifecycle.ResourceProvider) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Method(java.lang.reflect.Method) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 14 with MethodStats

use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.

the class OAuthJwtAuthenticatorImpl method getSignedJwt.

/**
 * Get signed jwt info.
 *
 * @param accessToken JWT token
 * @return SignedJWTInfo : Signed token info
 */
@MethodStats
private SignedJWTInfo getSignedJwt(String accessToken) throws ParseException {
    SignedJWT signedJWT = SignedJWT.parse(accessToken);
    JWTClaimsSet jwtClaimsSet = signedJWT.getJWTClaimsSet();
    return new SignedJWTInfo(accessToken, signedJWT, jwtClaimsSet);
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 15 with MethodStats

use of org.wso2.carbon.apimgt.rest.api.util.MethodStats 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)

Aggregations

MethodStats (org.wso2.carbon.apimgt.gateway.MethodStats)15 MethodStats (org.wso2.carbon.apimgt.rest.api.util.MethodStats)11 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)8 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)6 Timer (org.wso2.carbon.metrics.manager.Timer)6 TracingSpan (org.wso2.carbon.apimgt.tracing.TracingSpan)5 TracingTracer (org.wso2.carbon.apimgt.tracing.TracingTracer)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)3 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)3 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 TreeMap (java.util.TreeMap)2 AuthenticationException (org.apache.cxf.interceptor.security.AuthenticationException)2 Mediator (org.apache.synapse.Mediator)2 AuthenticationResponse (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse)2