Search in sources :

Example 6 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project digilib by robcast.

the class OpenIdAuthnOps method getUserRoles.

/* (non-Javadoc)
     * @see digilib.auth.AuthnOps#getUserRoles(digilib.conf.DigilibRequest)
     */
@Override
public List<String> getUserRoles(DigilibRequest request) throws AuthOpException {
    /*
         * try token parameter first
         */
    String id_token = request.getAsString("id_token");
    if (id_token == null || id_token.isEmpty()) {
        /*
             * try token cookie next
             */
        HttpServletRequest srvReq = ((DigilibServletRequest) request).getServletRequest();
        Cookie[] cookies = srvReq.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(tokenCookieName)) {
                    id_token = c.getValue();
                    break;
                }
            }
        }
        if (id_token == null || id_token.isEmpty()) {
            logger.error("Missing id token!");
            return null;
        }
    }
    // the first JwtConsumer is just used to parse the JWT into a JwtContext object.
    try {
        JwtContext jwtContext = firstPassJwtConsumer.process(id_token);
        // extract issuer
        String issuer = jwtContext.getJwtClaims().getIssuer();
        // get validating consumer for this issuer
        JwtConsumer secondPassJwtConsumer = idpJwtConsumers.get(issuer);
        if (secondPassJwtConsumer == null) {
            logger.error("Unknown id token issuer: " + issuer);
            return null;
        }
        // validate token
        secondPassJwtConsumer.processContext(jwtContext);
        JwtClaims claims = jwtContext.getJwtClaims();
        String sub = claims.getSubject();
        // get roles
        List<String> provided = idpRoles.get(issuer);
        logger.debug("Roles provided by id_token (sub='" + sub + "'): " + provided);
        return provided;
    } catch (InvalidJwtException | MalformedClaimException e) {
        logger.error("Error validating id token: " + e.getMessage());
        return null;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) DigilibServletRequest(digilib.conf.DigilibServletRequest) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext)

Example 7 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer 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 8 with JwtConsumer

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

the class JwtAuthenticationServiceImplTest method getJwks.

@Test
public void getJwks() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    webClient.login("alice");
    // this call triggers the creation of a RSA key in RSAConfidentialKey::getPrivateKey
    String token = getToken(webClient);
    String jwksPayload = webClient.goTo("jwt-auth/jwk-set", "application/json").getWebResponse().getContentAsString();
    System.out.println(jwksPayload);
    JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwksPayload);
    JwksVerificationKeyResolver jwksResolver = new JwksVerificationKeyResolver(jsonWebKeySet.getJsonWebKeys());
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKeyResolver(// verify the sign with the public key
    jwksResolver).build();
    JwtClaims claims = jwtConsumer.processToClaims(token);
    Assert.assertEquals("alice", 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("alice", userContext.get("id"));
    Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
    Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Also used : User(hudson.model.User) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Mailer(hudson.tasks.Mailer) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) Map(java.util.Map) Test(org.junit.Test)

Example 9 with JwtConsumer

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

the class JwtTokenVerifierImpl method validate.

/**
 * @return
 *      null if the JWT token is not present
 * @throws Exception
 *      if the JWT token is present but invalid
 */
@CheckForNull
private Authentication validate(HttpServletRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        return null;
    }
    String token = authHeader.substring("Bearer ".length());
    JsonWebStructure jws = parse(token);
    if (jws == null) {
        return null;
    }
    try {
        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");
        }
        SigningPublicKey publicKey = JwtSigningKeyProvider.toPublicKey(kid);
        if (publicKey == null) {
            throw new ServiceException.UnexpectedErrorException("Invalid kid=" + kid);
        }
        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
        publicKey.getKey()).build();
        try {
            JwtContext context = jwtConsumer.process(token);
            JwtClaims claims = context.getJwtClaims();
            String subject = claims.getSubject();
            if (subject.equals("anonymous")) {
                // if anonymous, we do not bother checking expiration
                return Jenkins.ANONYMOUS2;
            } else {
                // If not anonymous user, get Authentication object associated with this claim
                // We give a change to the authentication store to inspect the claims and if expired it might
                // do cleanup of associated Authentication object for example.
                JwtAuthenticationStore authenticationStore = getJwtStore(claims.getClaimsMap());
                Authentication authentication = authenticationStore.getAuthentication(claims.getClaimsMap());
                // Now check if token expired
                NumericDate expirationTime = claims.getExpirationTime();
                if (expirationTime.isBefore(NumericDate.now())) {
                    throw new ServiceException.UnauthorizedException("Invalid JWT token: expired");
                }
                return authentication;
            }
        } 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) SigningPublicKey(io.jenkins.blueocean.auth.jwt.SigningPublicKey) 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) JwtAuthenticationStore(io.jenkins.blueocean.auth.jwt.JwtAuthenticationStore) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) Authentication(org.springframework.security.core.Authentication) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) CheckForNull(javax.annotation.CheckForNull)

Example 10 with JwtConsumer

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

the class JwtAuthenticationServiceImplTest method getToken.

@Test
public void getToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient.login("alice");
    String token = getToken(webClient);
    Assert.assertNotNull(token);
    JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
    Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
    JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
    System.out.println(token);
    System.out.println(jsw);
    String kid = jsw.getHeader("kid");
    Assert.assertNotNull(kid);
    Page 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());
    System.out.println(jsonObject.toString());
    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("alice", 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("alice", userContext.get("id"));
    Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
    Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Also used : User(hudson.model.User) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Mailer(hudson.tasks.Mailer) 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)

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