Search in sources :

Example 16 with JwtClaims

use of org.jose4j.jwt.JwtClaims 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 17 with JwtClaims

use of org.jose4j.jwt.JwtClaims 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)

Example 18 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project java by kubernetes-client.

the class TestUtils method generateJWT.

/**
 * Utility for generating JWTs
 *
 * @param uid Maps to the sub claim
 * @param issuer URL of the issuer
 * @param signing Private key to sign the JWT
 * @param dos Determines at what time point the JWT should be generated
 * @return
 * @throws Exception
 */
public static String generateJWT(String uid, String issuer, PrivateKey signing, DateOptions dos) throws Exception {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    ArrayList<String> audiences = new ArrayList<String>();
    claims.setSubject(uid);
    claims.setGeneratedJwtId();
    // a unique identifier for the token
    claims.setGeneratedJwtId();
    if (dos == DateOptions.Now) {
        // when the token was issued/created (now)
        claims.setIssuedAtToNow();
        claims.setNotBeforeMinutesInThePast(// time before which the token is not yet valid (2 minutes ago)
        60000 / 1000 / 60);
        claims.setExpirationTimeMinutesInTheFuture(// time before which the token is not yet valid (2 minutes ago)
        60000 / 1000 / 60);
    }
    if (dos == DateOptions.Past) {
        claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() - 120000L));
        claims.setNotBeforeMinutesInThePast(// time before which the token is not yet valid (2 minutes ago)
        4);
        claims.setExpirationTimeMinutesInTheFuture(// time before which the token is not yet valid (2 minutes ago)
        -1);
    }
    if (dos == DateOptions.Future) {
        claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() + 120000L));
        claims.setNotBeforeMinutesInThePast(// time before which the token is not yet valid (2 minutes ago)
        -1);
        claims.setExpirationTimeMinutesInTheFuture(// time before which the token is not yet valid (2 minutes ago)
        4);
    }
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(signing);
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    return jws.getCompactSerialization();
}
Also used : JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) ArrayList(java.util.ArrayList)

Example 19 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project box-java-sdk by box.

the class BoxDeveloperEditionAPIConnectionTest method getRequestMatcher.

private RequestMatcherExtension getRequestMatcher(final String tokenPath) {
    return new RequestMatcherExtension() {

        @Override
        public MatchResult match(Request request, Parameters parameters) {
            if (!request.getMethod().equals(RequestMethod.POST) || !request.getUrl().equals(tokenPath)) {
                return MatchResult.noMatch();
            }
            Assert.assertNotNull("JTI should be saved from previous request", BoxDeveloperEditionAPIConnectionTest.this.jtiClaim);
            try {
                JwtClaims claims = BoxDeveloperEditionAPIConnectionTest.this.getClaimsFromRequest(request);
                String jti = claims.getJwtId();
                long expTimestamp = claims.getExpirationTime().getValue();
                Assert.assertNotEquals("JWT should have a new timestamp", 1511003910L, expTimestamp);
                Assert.assertNotEquals("JWT should have a new jti claim", BoxDeveloperEditionAPIConnectionTest.this.jtiClaim, jti);
            } catch (Exception ex) {
                Assert.fail("Could not parse JWT when request is retried: " + ex.getMessage());
            }
            return MatchResult.exactMatch();
        }
    };
}
Also used : Parameters(com.github.tomakehurst.wiremock.extension.Parameters) JwtClaims(org.jose4j.jwt.JwtClaims) Request(com.github.tomakehurst.wiremock.http.Request) RequestMatcherExtension(com.github.tomakehurst.wiremock.matching.RequestMatcherExtension)

Example 20 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project box-java-sdk by box.

the class BoxDeveloperEditionAPIConnection method constructJWTAssertion.

private String constructJWTAssertion(NumericDate now) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(this.getClientID());
    claims.setAudience(JWT_AUDIENCE);
    if (now == null) {
        claims.setExpirationTimeMinutesInTheFuture(0.5f);
    } else {
        now.addSeconds(30L);
        claims.setExpirationTime(now);
    }
    claims.setSubject(this.entityID);
    claims.setClaim("box_sub_type", this.entityType.toString());
    claims.setGeneratedJwtId(64);
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(this.decryptPrivateKey());
    jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
    jws.setHeader("typ", "JWT");
    if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
        jws.setHeader("kid", this.publicKeyID);
    }
    String assertion;
    try {
        assertion = jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
    }
    return assertion;
}
Also used : JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException)

Aggregations

JwtClaims (org.jose4j.jwt.JwtClaims)210 Test (org.junit.Test)90 JsonWebSignature (org.jose4j.jws.JsonWebSignature)51 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)25 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)25 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)25 JsonWebEncryption (org.jose4j.jwe.JsonWebEncryption)22 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)21 JoseException (org.jose4j.lang.JoseException)19 Map (java.util.Map)18 lombok.val (lombok.val)15 Test (org.junit.jupiter.api.Test)15 JwtContext (org.jose4j.jwt.consumer.JwtContext)12 DefaultJWTCallerPrincipal (io.smallrye.jwt.auth.principal.DefaultJWTCallerPrincipal)11 HashMap (java.util.HashMap)9 NumericDate (org.jose4j.jwt.NumericDate)9 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)9 JsonWebToken (org.eclipse.microprofile.jwt.JsonWebToken)8 SecretKey (javax.crypto.SecretKey)7 KeyStoreException (java.security.KeyStoreException)6