Search in sources :

Example 1 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project blueocean-plugin by jenkinsci.

the class JwtImplTest method anonymousUserToken.

@Test
public void anonymousUserToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    Page page = webClient.goTo("jwt-auth/token/", null);
    String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
    Assert.assertNotNull(token);
    JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
    Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
    JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
    String kid = jsw.getHeader("kid");
    Assert.assertNotNull(kid);
    page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
    //        for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
    //            System.out.println(valuePair);
    //        }
    JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
    RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKey(// verify the sign with the public key
    rsaJsonWebKey.getKey()).build();
    JwtClaims claims = jwtConsumer.processToClaims(token);
    Assert.assertEquals("anonymous", claims.getSubject());
    Map<String, Object> claimMap = claims.getClaimsMap();
    Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
    Map<String, String> userContext = (Map<String, String>) context.get("user");
    Assert.assertEquals("anonymous", userContext.get("id"));
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Page(com.gargoylesoftware.htmlunit.Page) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONObject(net.sf.json.JSONObject) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Map(java.util.Map) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) Test(org.junit.Test)

Example 2 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationToken method validate.

private static JwtClaims validate(StaplerRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServiceException.UnauthorizedException("JWT token not found");
    }
    String token = authHeader.substring("Bearer ".length());
    try {
        JsonWebStructure jws = JsonWebStructure.fromCompactSerialization(token);
        String alg = jws.getAlgorithmHeaderValue();
        if (alg == null || !alg.equals(RSA_USING_SHA256)) {
            logger.error(String.format("Invalid JWT token: unsupported algorithm in header, found %s, expected %s", alg, RSA_USING_SHA256));
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        }
        String kid = jws.getKeyIdHeaderValue();
        if (kid == null) {
            logger.error("Invalid JWT token: missing kid");
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        }
        JwtToken.JwtRsaDigitalSignatureKey key = new JwtToken.JwtRsaDigitalSignatureKey(kid);
        try {
            if (!key.exists()) {
                throw new ServiceException.NotFoundException(String.format("kid %s not found", kid));
            }
        } catch (IOException e) {
            logger.error(String.format("Error reading RSA key for id %s: %s", kid, e.getMessage()), e);
            throw new ServiceException.UnexpectedErrorException("Unexpected error: " + e.getMessage(), e);
        }
        JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setRequireJwtId().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
        30).setRequireSubject().setVerificationKey(// verify the sign with the public key
        key.getPublicKey()).build();
        try {
            JwtContext context = jwtConsumer.process(token);
            JwtClaims claims = context.getJwtClaims();
            //check if token expired
            NumericDate expirationTime = claims.getExpirationTime();
            if (expirationTime.isBefore(NumericDate.now())) {
                throw new ServiceException.UnauthorizedException("Invalid JWT token: expired");
            }
            return claims;
        } catch (InvalidJwtException e) {
            logger.error("Invalid JWT token: " + e.getMessage(), e);
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        } catch (MalformedClaimException e) {
            logger.error(String.format("Error reading sub header for token %s", jws.getPayload()), e);
            throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
        }
    } catch (JoseException e) {
        logger.error("Error parsing JWT token: " + e.getMessage(), e);
        throw new ServiceException.UnauthorizedException("Invalid JWT Token: " + e.getMessage());
    }
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JoseException(org.jose4j.lang.JoseException) JwtContext(org.jose4j.jwt.consumer.JwtContext) IOException(java.io.IOException) JwtToken(io.jenkins.blueocean.auth.jwt.JwtToken) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JsonWebStructure(org.jose4j.jwx.JsonWebStructure)

Example 3 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project light-4j by networknt.

the class Http2ClientIT method isTokenExpired.

private static boolean isTokenExpired(String authorization) {
    boolean expired = false;
    String jwt = getJwtFromAuthorization(authorization);
    if (jwt != null) {
        try {
            JwtConsumer consumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
            JwtContext jwtContext = consumer.process(jwt);
            JwtClaims jwtClaims = jwtContext.getJwtClaims();
            try {
                if ((NumericDate.now().getValue() - 60) >= jwtClaims.getExpirationTime().getValue()) {
                    expired = true;
                }
            } catch (MalformedClaimException e) {
                logger.error("MalformedClaimException:", e);
            }
        } catch (InvalidJwtException e) {
            e.printStackTrace();
        }
    }
    return expired;
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext)

Example 4 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project light-4j by networknt.

the class OauthHelperTest method isTokenExpired.

private static boolean isTokenExpired(String authorization) {
    boolean expired = false;
    String jwt = getJwtFromAuthorization(authorization);
    if (jwt != null) {
        JwtConsumer consumer = new JwtConsumerBuilder().setDisableRequireSignature().setSkipSignatureVerification().build();
        try {
            consumer.processToClaims(jwt);
        } catch (InvalidJwtException e) {
            if (e.hasExpired())
                expired = true;
        }
    }
    return expired;
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer)

Example 5 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project wildfly-swarm by wildfly-swarm.

the class DefaultJWTCallerPrincipalFactory method parse.

@Override
public JWTCallerPrincipal parse(final String token, final JWTAuthContextInfo authContextInfo) throws ParseException {
    JWTCallerPrincipal principal = null;
    try {
        JwtConsumerBuilder builder = new JwtConsumerBuilder().setRequireExpirationTime().setRequireSubject().setSkipDefaultAudienceValidation().setExpectedIssuer(authContextInfo.getIssuedBy()).setVerificationKey(authContextInfo.getSignerKey()).setJwsAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256));
        if (authContextInfo.getExpGracePeriodSecs() > 0) {
            builder.setAllowedClockSkewInSeconds(authContextInfo.getExpGracePeriodSecs());
        } else {
            builder.setEvaluationTime(NumericDate.fromSeconds(0));
        }
        JwtConsumer jwtConsumer = builder.build();
        JwtContext jwtContext = jwtConsumer.process(token);
        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 DefaultJWTCallerPrincipal(token, type, claimsSet, principalName);
    } catch (InvalidJwtException e) {
        throw new ParseException("Failed to verify token", e);
    } catch (MalformedClaimException e) {
        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) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext) AlgorithmConstraints(org.jose4j.jwa.AlgorithmConstraints)

Aggregations

JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)19 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)18 JwtClaims (org.jose4j.jwt.JwtClaims)15 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)11 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)10 JwtContext (org.jose4j.jwt.consumer.JwtContext)9 Map (java.util.Map)6 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)6 JSONObject (net.sf.json.JSONObject)5 Test (org.junit.Test)5 JenkinsRule (org.jvnet.hudson.test.JenkinsRule)5 Page (com.gargoylesoftware.htmlunit.Page)4 RsaJsonWebKey (org.jose4j.jwk.RsaJsonWebKey)4 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JoseException (org.jose4j.lang.JoseException)4 User (hudson.model.User)3 Mailer (hudson.tasks.Mailer)3 AlgorithmConstraints (org.jose4j.jwa.AlgorithmConstraints)3 JwksVerificationKeyResolver (org.jose4j.keys.resolvers.JwksVerificationKeyResolver)3 ServiceException (io.jenkins.blueocean.commons.ServiceException)2