Search in sources :

Example 1 with JwtException

use of org.apache.cxf.rs.security.jose.jwt.JwtException in project cxf by apache.

the class AbstractAccessTokenValidator method getAccessTokenValidation.

/**
 * Get the access token
 */
protected AccessTokenValidation getAccessTokenValidation(String authScheme, String authSchemeData, MultivaluedMap<String, String> extraProps) {
    if (dataProvider == null && tokenHandlers.isEmpty()) {
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    AccessTokenValidation accessTokenV = null;
    if (maxValidationDataCacheSize > 0) {
        accessTokenV = accessTokenValidations.get(authSchemeData);
    }
    ServerAccessToken localAccessToken = null;
    if (accessTokenV == null) {
        // Get the registered handler capable of processing the token
        AccessTokenValidator handler = findTokenValidator(authScheme);
        if (handler != null) {
            try {
                // Convert the HTTP Authorization scheme data into a token
                accessTokenV = handler.validateAccessToken(getMessageContext(), authScheme, authSchemeData, extraProps);
            } catch (RuntimeException ex) {
                AuthorizationUtils.throwAuthorizationFailure(Collections.singleton(authScheme), realm);
            }
        }
        // Default processing if no registered providers available
        if (accessTokenV == null && dataProvider != null && authScheme.equals(DEFAULT_AUTH_SCHEME)) {
            try {
                String cacheKey = authSchemeData;
                if (!persistJwtEncoding) {
                    JoseJwtConsumer theConsumer = jwtTokenConsumer == null ? new JoseJwtConsumer() : jwtTokenConsumer;
                    JwtToken token = theConsumer.getJwtToken(authSchemeData);
                    cacheKey = token.getClaims().getTokenId();
                }
                localAccessToken = dataProvider.getAccessToken(cacheKey);
            } catch (JwtException | OAuthServiceException ex) {
            // to be handled next
            }
            if (localAccessToken == null) {
                AuthorizationUtils.throwAuthorizationFailure(Collections.singleton(authScheme), realm);
            }
            accessTokenV = new AccessTokenValidation(localAccessToken);
        }
    }
    if (accessTokenV == null) {
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    // Check if token is still valid
    if (OAuthUtils.isExpired(accessTokenV.getTokenIssuedAt(), accessTokenV.getTokenLifetime())) {
        if (localAccessToken != null) {
            removeAccessToken(localAccessToken);
        } else if (maxValidationDataCacheSize > 0) {
            accessTokenValidations.remove(authSchemeData);
        }
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    // Check nbf property
    if (accessTokenV.getTokenNotBefore() > 0 && accessTokenV.getTokenNotBefore() > System.currentTimeMillis() / 1000L) {
        AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    }
    if (maxValidationDataCacheSize > 0) {
        if (accessTokenValidations.size() >= maxValidationDataCacheSize) {
            // or delete the ones expiring sooner than others, etc
            accessTokenValidations.clear();
        }
        accessTokenValidations.put(authSchemeData, accessTokenV);
    }
    return accessTokenV;
}
Also used : AccessTokenValidator(org.apache.cxf.rs.security.oauth2.provider.AccessTokenValidator) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException) JoseJwtConsumer(org.apache.cxf.rs.security.jose.jwt.JoseJwtConsumer)

Example 2 with JwtException

use of org.apache.cxf.rs.security.jose.jwt.JwtException in project cxf by apache.

the class TokenIntrospectionService method getTokenIntrospection.

@POST
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public TokenIntrospection getTokenIntrospection(@Encoded MultivaluedMap<String, String> params) {
    checkSecurityContext();
    String tokenId = params.getFirst(OAuthConstants.TOKEN_ID);
    if (!persistJwtEncoding) {
        try {
            JoseJwtConsumer theConsumer = jwtTokenConsumer == null ? new JoseJwtConsumer() : jwtTokenConsumer;
            JwtToken token = theConsumer.getJwtToken(tokenId);
            tokenId = token.getClaims().getTokenId();
        } catch (JwtException ex) {
            return new TokenIntrospection(false);
        }
    }
    ServerAccessToken at = dataProvider.getAccessToken(tokenId);
    if (at == null || OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn())) {
        return new TokenIntrospection(false);
    }
    TokenIntrospection response = new TokenIntrospection(true);
    response.setClientId(at.getClient().getClientId());
    if (!at.getScopes().isEmpty()) {
        response.setScope(OAuthUtils.convertPermissionsToScope(at.getScopes()));
    }
    UserSubject userSubject = at.getSubject();
    if (userSubject != null) {
        response.setUsername(at.getSubject().getLogin());
        if (userSubject.getId() != null) {
            response.setSub(userSubject.getId());
        }
    }
    if (!StringUtils.isEmpty(at.getAudiences())) {
        response.setAud(at.getAudiences());
    }
    if (at.getIssuer() != null) {
        response.setIss(at.getIssuer());
    }
    response.setIat(at.getIssuedAt());
    if (at.getExpiresIn() > 0) {
        response.setExp(at.getIssuedAt() + at.getExpiresIn());
    }
    if (at.getNotBefore() > 0) {
        response.setNbf(at.getNotBefore());
    }
    response.setTokenType(at.getTokenType());
    if (reportExtraTokenProperties) {
        response.getExtensions().putAll(at.getExtraProperties());
    }
    return response;
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) TokenIntrospection(org.apache.cxf.rs.security.oauth2.common.TokenIntrospection) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException) JoseJwtConsumer(org.apache.cxf.rs.security.jose.jwt.JoseJwtConsumer) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 3 with JwtException

use of org.apache.cxf.rs.security.jose.jwt.JwtException in project cxf by apache.

the class JoseConsumer method getData.

public String getData(String data) {
    super.checkProcessRequirements();
    if (isJweRequired()) {
        JweCompactConsumer jweConsumer = new JweCompactConsumer(data);
        JweDecryptionProvider theDecryptor = getInitializedDecryptionProvider(jweConsumer.getJweHeaders());
        if (theDecryptor == null) {
            throw new JwtException("Unable to decrypt JWT");
        }
        if (!isJwsRequired()) {
            return jweConsumer.getDecryptedContentText(theDecryptor);
        }
        JweDecryptionOutput decOutput = theDecryptor.decrypt(data);
        data = decOutput.getContentText();
    }
    JwsCompactConsumer jwsConsumer = new JwsCompactConsumer(data);
    if (isJwsRequired()) {
        JwsSignatureVerifier theSigVerifier = getInitializedSignatureVerifier(jwsConsumer.getJwsHeaders());
        if (theSigVerifier == null) {
            throw new JwtException("Unable to validate JWT");
        }
        if (!jwsConsumer.verifySignatureWith(theSigVerifier)) {
            throw new JwtException("Invalid Signature");
        }
    }
    return jwsConsumer.getDecodedJwsPayload();
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JweDecryptionOutput(org.apache.cxf.rs.security.jose.jwe.JweDecryptionOutput) JwsCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsCompactConsumer) JweCompactConsumer(org.apache.cxf.rs.security.jose.jwe.JweCompactConsumer) JweDecryptionProvider(org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException)

Example 4 with JwtException

use of org.apache.cxf.rs.security.jose.jwt.JwtException in project cxf by apache.

the class OidcClaimsValidator method validateJwtClaims.

/**
 * Validate core JWT claims
 * @param claims the claims
 * @param clientId OAuth2 client id
 * @param validateClaimsAlways if set to true then enforce that the claims
 *                             to be validated must be set
 */
public void validateJwtClaims(JwtClaims claims, String clientId, boolean validateClaimsAlways) {
    // validate the issuer
    String issuer = claims.getIssuer();
    if (issuer == null && validateClaimsAlways) {
        throw new OAuthServiceException("Invalid issuer");
    }
    if (supportSelfIssuedProvider && issuerId == null && issuer != null && SELF_ISSUED_ISSUER.equals(issuer)) {
        validateSelfIssuedProvider(claims, clientId, validateClaimsAlways);
    } else {
        if (issuer != null && !issuer.equals(issuerId)) {
            throw new OAuthServiceException("Invalid issuer");
        }
        // validate subject
        if (claims.getSubject() == null) {
            throw new OAuthServiceException("Invalid subject");
        }
        // validate authorized party
        String authorizedParty = (String) claims.getClaim(IdToken.AZP_CLAIM);
        if (authorizedParty != null && !authorizedParty.equals(clientId)) {
            throw new OAuthServiceException("Invalid authorized party");
        }
        // validate audience
        List<String> audiences = claims.getAudiences();
        if (StringUtils.isEmpty(audiences) && validateClaimsAlways || !StringUtils.isEmpty(audiences) && !audiences.contains(clientId)) {
            throw new OAuthServiceException("Invalid audience");
        }
        // If strict time validation: if no issuedTime claim is set then an expiresAt claim must be set
        // Otherwise: validate only if expiresAt claim is set
        boolean expiredRequired = validateClaimsAlways || strictTimeValidation && claims.getIssuedAt() == null;
        try {
            JwtUtils.validateJwtExpiry(claims, getClockOffset(), expiredRequired);
        } catch (JwtException ex) {
            throw new OAuthServiceException("ID Token has expired", ex);
        }
        // If strict time validation: If no expiresAt claim is set then an issuedAt claim must be set
        // Otherwise: validate only if issuedAt claim is set
        boolean issuedAtRequired = validateClaimsAlways || strictTimeValidation && claims.getExpiryTime() == null;
        try {
            JwtUtils.validateJwtIssuedAt(claims, getTtl(), getClockOffset(), issuedAtRequired);
        } catch (JwtException ex) {
            throw new OAuthServiceException("Invalid issuedAt claim", ex);
        }
        // Validate nbf - but don't require it to be present
        try {
            JwtUtils.validateJwtNotBefore(claims, getClockOffset(), false);
        } catch (JwtException ex) {
            throw new OAuthServiceException("ID Token can not be used yet", ex);
        }
    }
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException)

Example 5 with JwtException

use of org.apache.cxf.rs.security.jose.jwt.JwtException in project cxf by apache.

the class OidcRpAuthenticationFilter method checkSecurityContext.

protected boolean checkSecurityContext(ContainerRequestContext rc) {
    OidcClientTokenContext tokenContext = (OidcClientTokenContext) stateManager.getClientTokenContext(mc);
    if (tokenContext == null) {
        return false;
    }
    IdToken idToken = tokenContext.getIdToken();
    try {
        // If ID token has expired then the context is no longer valid
        JwtUtils.validateJwtExpiry(idToken, 0, idToken.getExpiryTime() != null);
    } catch (JwtException ex) {
        stateManager.removeClientTokenContext(new MessageContextImpl(JAXRSUtils.getCurrentMessage()));
        return false;
    }
    OidcClientTokenContextImpl newTokenContext = new OidcClientTokenContextImpl();
    newTokenContext.setToken(tokenContext.getToken());
    newTokenContext.setIdToken(idToken);
    newTokenContext.setUserInfo(tokenContext.getUserInfo());
    newTokenContext.setState(toRequestState(rc));
    JAXRSUtils.getCurrentMessage().setContent(ClientTokenContext.class, newTokenContext);
    OidcSecurityContext oidcSecCtx = new OidcSecurityContext(newTokenContext);
    oidcSecCtx.setRoleClaim(roleClaim);
    rc.setSecurityContext(oidcSecCtx);
    return true;
}
Also used : IdToken(org.apache.cxf.rs.security.oidc.common.IdToken) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Aggregations

JwtException (org.apache.cxf.rs.security.jose.jwt.JwtException)5 JoseJwtConsumer (org.apache.cxf.rs.security.jose.jwt.JoseJwtConsumer)2 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)2 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)2 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)2 Consumes (javax.ws.rs.Consumes)1 POST (javax.ws.rs.POST)1 Produces (javax.ws.rs.Produces)1 MessageContextImpl (org.apache.cxf.jaxrs.ext.MessageContextImpl)1 JweCompactConsumer (org.apache.cxf.rs.security.jose.jwe.JweCompactConsumer)1 JweDecryptionOutput (org.apache.cxf.rs.security.jose.jwe.JweDecryptionOutput)1 JweDecryptionProvider (org.apache.cxf.rs.security.jose.jwe.JweDecryptionProvider)1 JwsCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsCompactConsumer)1 JwsSignatureVerifier (org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier)1 AccessTokenValidation (org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation)1 TokenIntrospection (org.apache.cxf.rs.security.oauth2.common.TokenIntrospection)1 UserSubject (org.apache.cxf.rs.security.oauth2.common.UserSubject)1 AccessTokenValidator (org.apache.cxf.rs.security.oauth2.provider.AccessTokenValidator)1 IdToken (org.apache.cxf.rs.security.oidc.common.IdToken)1