Search in sources :

Example 1 with JWTAuthConfiguration

use of org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration in project tomee by apache.

the class JsonWebTokenValidator method validate.

public JsonWebToken validate(final String token) throws ParseException {
    final JWTAuthConfiguration authConfiguration = verificationKey != null ? JWTAuthConfiguration.authConfiguration(verificationKey, issuer, allowNoExpiryClaim) : JWTAuthConfiguration.authConfiguration(verificationKeys, issuer, allowNoExpiryClaim);
    JWTCallerPrincipal principal;
    try {
        final JwtConsumerBuilder builder = new JwtConsumerBuilder().setRelaxVerificationKeyValidation().setRequireSubject().setSkipDefaultAudienceValidation().setJwsAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256, AlgorithmIdentifiers.RSA_USING_SHA384, AlgorithmIdentifiers.RSA_USING_SHA512));
        if (authConfiguration.getIssuer() != null) {
            builder.setExpectedIssuer(authConfiguration.getIssuer());
        }
        if (authConfiguration.getExpGracePeriodSecs() > 0) {
            builder.setAllowedClockSkewInSeconds(authConfiguration.getExpGracePeriodSecs());
        } else {
            builder.setEvaluationTime(NumericDate.fromSeconds(0));
        }
        if (authConfiguration.isSingleKey()) {
            builder.setVerificationKey(authConfiguration.getPublicKey());
        } else {
            builder.setVerificationKeyResolver(new JwksVerificationKeyResolver(authConfiguration.getPublicKeys()));
        }
        final JwtConsumer jwtConsumer = builder.build();
        final JwtContext jwtContext = jwtConsumer.process(token);
        final String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
        // Validate the JWT and process it to the Claims
        jwtConsumer.processContext(jwtContext);
        JwtClaims claimsSet = jwtContext.getJwtClaims();
        // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
        String principalName = claimsSet.getClaimValue("upn", String.class);
        if (principalName == null) {
            principalName = claimsSet.getClaimValue("preferred_username", String.class);
            if (principalName == null) {
                principalName = claimsSet.getSubject();
            }
        }
        claimsSet.setClaim(Claims.raw_token.name(), token);
        principal = new JWTCallerPrincipal(token, type, claimsSet, principalName);
    } catch (final InvalidJwtException e) {
        VALIDATION.warning(e.getMessage());
        throw new ParseException("Failed to verify token", e);
    } catch (final MalformedClaimException e) {
        VALIDATION.warning(e.getMessage());
        throw new ParseException("Failed to verify token claims", e);
    }
    return principal;
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JWTAuthConfiguration(org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JWTCallerPrincipal(org.apache.tomee.microprofile.jwt.principal.JWTCallerPrincipal) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints)

Example 2 with JWTAuthConfiguration

use of org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration in project tomee by apache.

the class MPJWTFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final Optional<JWTAuthConfiguration> authContextInfo = getAuthContextInfo();
    if (!authContextInfo.isPresent()) {
        chain.doFilter(request, response);
        return;
    }
    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    // now wrap the httpServletRequest and override the principal so CXF can propagate into the SecurityContext
    try {
        final MPJWTServletRequestWrapper wrappedRequest = new MPJWTServletRequestWrapper(httpServletRequest, authContextInfo.get());
        chain.doFilter(wrappedRequest, response);
        Object state = request.getAttribute("MP_JWT_PRE_LOGIN_STATE");
        final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
        if (TomcatSecurityService.class.isInstance(securityService) && state != null) {
            final TomcatSecurityService tomcatSecurityService = TomcatSecurityService.class.cast(securityService);
            tomcatSecurityService.exitWebApp(state);
        }
    } catch (final Exception e) {
        // or users to add it into their webapp for scanning or into the Application itself
        if (MPJWTException.class.isInstance(e)) {
            final MPJWTException jwtException = MPJWTException.class.cast(e);
            HttpServletResponse.class.cast(response).sendError(jwtException.getStatus(), jwtException.getMessage());
        } else if (MPJWTException.class.isInstance(e.getCause())) {
            final MPJWTException jwtException = MPJWTException.class.cast(e.getCause());
            HttpServletResponse.class.cast(response).sendError(jwtException.getStatus(), jwtException.getMessage());
        } else {
            throw e;
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JWTAuthConfiguration(org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration) SecurityService(org.apache.openejb.spi.SecurityService) TomcatSecurityService(org.apache.tomee.catalina.TomcatSecurityService) HttpServletResponse(javax.servlet.http.HttpServletResponse) TomcatSecurityService(org.apache.tomee.catalina.TomcatSecurityService) ServletException(javax.servlet.ServletException) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) IOException(java.io.IOException)

Example 3 with JWTAuthConfiguration

use of org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration in project tomee by apache.

the class PublicKeyAsJWKSTest method validateJWKS.

@Test
public void validateJWKS() throws Exception {
    System.setProperty(Names.VERIFIER_PUBLIC_KEY, "");
    System.setProperty(Names.VERIFIER_PUBLIC_KEY_LOCATION, "file://" + Paths.get("").toAbsolutePath().toString() + "/src/test/resources/signer-keyset4k.jwk");
    System.setProperty(Names.ISSUER, TCKConstants.TEST_ISSUER);
    final PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey4k.pem");
    final String kid = "publicKey4k";
    final String token = TokenUtils.generateTokenString(privateKey, kid, "/Token1.json", null, new HashMap<>());
    System.out.println("token = " + token);
    final JWTAuthConfigurationProperties JWTAuthConfigurationProperties = new JWTAuthConfigurationProperties();
    JWTAuthConfigurationProperties.init(null);
    final JWTAuthConfiguration jwtAuthConfiguration = JWTAuthConfigurationProperties.getJWTAuthConfiguration().orElseThrow(IllegalArgumentException::new);
    final JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder().setRequireExpirationTime().setRequireSubject().setSkipDefaultAudienceValidation().setExpectedIssuer(jwtAuthConfiguration.getIssuer()).setJwsAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, RSA_USING_SHA256)).setSkipDefaultAudienceValidation().setVerificationKey(jwtAuthConfiguration.getPublicKey());
    if (jwtAuthConfiguration.getExpGracePeriodSecs() > 0) {
        jwtConsumerBuilder.setAllowedClockSkewInSeconds(jwtAuthConfiguration.getExpGracePeriodSecs());
    } else {
        jwtConsumerBuilder.setEvaluationTime(NumericDate.fromSeconds(0));
    }
    if (jwtAuthConfiguration.isSingleKey()) {
        jwtConsumerBuilder.setVerificationKey(jwtAuthConfiguration.getPublicKey());
    } else {
        jwtConsumerBuilder.setVerificationKeyResolver(new JwksVerificationKeyResolver(jwtAuthConfiguration.getPublicKeys()));
    }
    final JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    final JwtContext jwtContext = jwtConsumer.process(token);
    Assert.assertEquals(jwtContext.getJwtClaims().getStringClaimValue("upn"), "jdoe@example.com");
}
Also used : PrivateKey(java.security.PrivateKey) JWTAuthConfiguration(org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JWTAuthConfigurationProperties(org.apache.tomee.microprofile.jwt.config.JWTAuthConfigurationProperties) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints) Test(org.testng.annotations.Test)

Aggregations

JWTAuthConfiguration (org.apache.tomee.microprofile.jwt.config.JWTAuthConfiguration)3 AlgorithmConstraints (org.jose4j.jwa.AlgorithmConstraints)2 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)2 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)2 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)2 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)2 JwtContext (org.jose4j.jwt.consumer.JwtContext)2 JwksVerificationKeyResolver (org.jose4j.keys.resolvers.JwksVerificationKeyResolver)2 IOException (java.io.IOException)1 PrivateKey (java.security.PrivateKey)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 SecurityService (org.apache.openejb.spi.SecurityService)1 TomcatSecurityService (org.apache.tomee.catalina.TomcatSecurityService)1 JWTAuthConfigurationProperties (org.apache.tomee.microprofile.jwt.config.JWTAuthConfigurationProperties)1 JWTCallerPrincipal (org.apache.tomee.microprofile.jwt.principal.JWTCallerPrincipal)1 JwtClaims (org.jose4j.jwt.JwtClaims)1 Test (org.testng.annotations.Test)1