Search in sources :

Example 11 with JWTValidationInfo

use of org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo in project carbon-apimgt by wso2.

the class JWTValidator method getJwtValidationInfo.

private JWTValidationInfo getJwtValidationInfo(SignedJWTInfo signedJWTInfo, String jti) throws APISecurityException {
    String jwtHeader = signedJWTInfo.getSignedJWT().getHeader().toString();
    String tenantDomain = GatewayUtils.getTenantDomain();
    JWTValidationInfo jwtValidationInfo = null;
    if (isGatewayTokenCacheEnabled && !SignedJWTInfo.ValidationStatus.NOT_VALIDATED.equals(signedJWTInfo.getValidationStatus())) {
        String cacheToken = (String) getGatewayTokenCache().get(jti);
        if (SignedJWTInfo.ValidationStatus.VALID.equals(signedJWTInfo.getValidationStatus()) && cacheToken != null) {
            if (getGatewayKeyCache().get(jti) != null) {
                JWTValidationInfo tempJWTValidationInfo = (JWTValidationInfo) getGatewayKeyCache().get(jti);
                checkTokenExpiration(jti, tempJWTValidationInfo, tenantDomain);
                jwtValidationInfo = tempJWTValidationInfo;
            }
        } else if (SignedJWTInfo.ValidationStatus.INVALID.equals(signedJWTInfo.getValidationStatus()) && getInvalidTokenCache().get(jti) != null) {
            if (log.isDebugEnabled()) {
                log.debug("Token retrieved from the invalid token cache. Token: " + GatewayUtils.getMaskedToken(jwtHeader));
            }
            log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader));
            jwtValidationInfo = new JWTValidationInfo();
            jwtValidationInfo.setValidationCode(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
            jwtValidationInfo.setValid(false);
        }
    }
    if (jwtValidationInfo == null) {
        try {
            jwtValidationInfo = jwtValidationService.validateJWTToken(signedJWTInfo);
            signedJWTInfo.setValidationStatus(jwtValidationInfo.isValid() ? SignedJWTInfo.ValidationStatus.VALID : SignedJWTInfo.ValidationStatus.INVALID);
            if (isGatewayTokenCacheEnabled) {
                // Add token to tenant token cache
                if (jwtValidationInfo.isValid()) {
                    getGatewayTokenCache().put(jti, tenantDomain);
                    getGatewayKeyCache().put(jti, jwtValidationInfo);
                } else {
                    getInvalidTokenCache().put(jti, tenantDomain);
                }
                if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                    // to remove the entry when the need occurs to clear this particular cache entry.
                    try {
                        // Start super tenant flow
                        PrivilegedCarbonContext.startTenantFlow();
                        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
                        // Add token to super tenant token cache
                        if (jwtValidationInfo.isValid()) {
                            getGatewayTokenCache().put(jti, tenantDomain);
                        } else {
                            getInvalidTokenCache().put(jti, tenantDomain);
                        }
                    } finally {
                        PrivilegedCarbonContext.endTenantFlow();
                    }
                }
            }
            return jwtValidationInfo;
        } catch (APIManagementException e) {
            throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
        }
    }
    return jwtValidationInfo;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Example 12 with JWTValidationInfo

use of org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo in project carbon-apimgt by wso2.

the class JWTValidator method generateAuthenticationContextForWS.

/**
 * Generate Authentication Context for WS API requests.
 *
 * @param jti                     JTI
 * @param jwtValidationInfo       JWTValidationInfo
 * @param apiKeyValidationInfoDTO APIKeyValidationInfoDTO
 * @param endUserToken            Enduser token
 * @param apiVersion              API Version
 * @return AuthenticationContext
 */
private AuthenticationContext generateAuthenticationContextForWS(String jti, JWTValidationInfo jwtValidationInfo, APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String endUserToken, String apiVersion) {
    AuthenticationContext context = GatewayUtils.generateAuthenticationContext(jti, jwtValidationInfo, apiKeyValidationInfoDTO, endUserToken, true);
    context.setApiVersion(apiVersion);
    return context;
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)

Example 13 with JWTValidationInfo

use of org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo in project carbon-apimgt by wso2.

the class JWTValidator method includeUserStoreClaimsIntoClaims.

private void includeUserStoreClaimsIntoClaims(JWTInfoDto jwtInfoDto) {
    JWTInfoDto localJWTInfoDto = new JWTInfoDto(jwtInfoDto);
    Map<String, String> userClaimsFromKeyManager = getUserClaimsFromKeyManager(localJWTInfoDto);
    JWTValidationInfo jwtValidationInfo = localJWTInfoDto.getJwtValidationInfo();
    if (jwtValidationInfo != null && jwtValidationInfo.getClaims() != null) {
        jwtValidationInfo.getClaims().putAll(userClaimsFromKeyManager);
    }
}
Also used : JWTInfoDto(org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Example 14 with JWTValidationInfo

use of org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo in project carbon-apimgt by wso2.

the class JWTValidator method validateTokenForWS.

/**
 * Validates token for Websocket requests.
 *
 * @param signedJWTInfo  SignedJWT Info
 * @param tokenSignature Token Signature
 * @param jti            JTI
 * @return JWT Validation Info
 * @throws APISecurityException If an error occurs
 */
private JWTValidationInfo validateTokenForWS(SignedJWTInfo signedJWTInfo, String tokenSignature, String jti) throws APISecurityException {
    JWTValidationInfo jwtValidationInfo;
    String jwtHeader = signedJWTInfo.getSignedJWT().getHeader().toString();
    jwtValidationInfo = getJwtValidationInfo(signedJWTInfo, jti);
    if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(tokenSignature)) {
        if (log.isDebugEnabled()) {
            log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.getMaskedToken(jwtHeader));
        }
        log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader));
        jwtValidationInfo.setValidationCode(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
        jwtValidationInfo.setValid(false);
    }
    return jwtValidationInfo;
}
Also used : JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Example 15 with JWTValidationInfo

use of org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo in project carbon-apimgt by wso2.

the class JWTValidator method authenticate.

/**
 * Authenticates the given request with a JWT token to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param signedJWTInfo The JWT token sent with the API request
 * @param synCtx   The message to be authenticated
 * @return an AuthenticationContext object which contains the authentication information
 * @throws APISecurityException in case of authentication failure
 */
@MethodStats
public AuthenticationContext authenticate(SignedJWTInfo signedJWTInfo, MessageContext synCtx) throws APISecurityException {
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    org.apache.axis2.context.MessageContext axis2MsgContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String httpMethod = (String) axis2MsgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    String jwtTokenIdentifier = getJWTTokenIdentifier(signedJWTInfo);
    String jwtHeader = signedJWTInfo.getSignedJWT().getHeader().toString();
    try {
        X509Certificate clientCertificate = Utils.getClientCertificate(axis2MsgContext);
        signedJWTInfo.setX509ClientCertificate(clientCertificate);
    } catch (APIManagementException e) {
        log.error("Error while obtaining client certificate. " + GatewayUtils.getMaskedToken(jwtHeader));
    }
    if (StringUtils.isNotEmpty(jwtTokenIdentifier)) {
        if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(jwtTokenIdentifier)) {
            if (log.isDebugEnabled()) {
                log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.getMaskedToken(jwtHeader));
            }
            log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader));
            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
        }
    }
    JWTValidationInfo jwtValidationInfo = getJwtValidationInfo(signedJWTInfo, jwtTokenIdentifier);
    if (jwtValidationInfo != null) {
        if (jwtValidationInfo.isValid()) {
            // Validate subscriptions
            APIKeyValidationInfoDTO apiKeyValidationInfoDTO;
            log.debug("Begin subscription validation via Key Manager: " + jwtValidationInfo.getKeyManager());
            apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(synCtx, jwtValidationInfo);
            if (log.isDebugEnabled()) {
                log.debug("Subscription validation via Key Manager. Status: " + apiKeyValidationInfoDTO.isAuthorized());
            }
            if (!apiKeyValidationInfoDTO.isAuthorized()) {
                log.debug("User is NOT authorized to access the Resource. API Subscription validation failed.");
                throw new APISecurityException(apiKeyValidationInfoDTO.getValidationStatus(), "User is NOT authorized to access the Resource. API Subscription validation failed.");
            }
            // Validate scopes
            validateScopes(apiContext, apiVersion, matchingResource, httpMethod, jwtValidationInfo, signedJWTInfo);
            synCtx.setProperty(APIMgtGatewayConstants.SCOPES, jwtValidationInfo.getScopes().toString());
            if (apiKeyValidationInfoDTO.isAuthorized()) {
                /*
                     * Set api.ut.apiPublisher of the subscribed api to the message context.
                     * This is necessary for the functionality of Publisher alerts.
                     * Set API_NAME of the subscribed api to the message context.
                     * */
                synCtx.setProperty(APIMgtGatewayConstants.API_PUBLISHER, apiKeyValidationInfoDTO.getApiPublisher());
                synCtx.setProperty("API_NAME", apiKeyValidationInfoDTO.getApiName());
                /* GraphQL Query Analysis Information */
                if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
                    synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, apiKeyValidationInfoDTO.getGraphQLMaxDepth());
                    synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, apiKeyValidationInfoDTO.getGraphQLMaxComplexity());
                }
                log.debug("JWT authentication successful.");
            }
            log.debug("JWT authentication successful.");
            String endUserToken = null;
            if (jwtGenerationEnabled) {
                JWTInfoDto jwtInfoDto = GatewayUtils.generateJWTInfoDto(null, jwtValidationInfo, apiKeyValidationInfoDTO, synCtx);
                endUserToken = generateAndRetrieveJWTToken(jwtTokenIdentifier, jwtInfoDto);
            }
            return GatewayUtils.generateAuthenticationContext(jwtTokenIdentifier, jwtValidationInfo, apiKeyValidationInfoDTO, endUserToken, true);
        } else {
            throw new APISecurityException(jwtValidationInfo.getValidationCode(), APISecurityConstants.getAuthenticationFailureMessage(jwtValidationInfo.getValidationCode()));
        }
    } else {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JWTInfoDto(org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) X509Certificate(javax.security.cert.X509Certificate) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Aggregations

JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)23 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)14 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)12 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)11 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)11 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)11 HashMap (java.util.HashMap)10 SignedJWT (com.nimbusds.jwt.SignedJWT)9 Cache (javax.cache.Cache)9 MessageContext (org.apache.synapse.MessageContext)9 Test (org.junit.Test)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)9 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)9 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)9 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)9 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)8 JWTInfoDto (org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4