Search in sources :

Example 71 with JwtClaims

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

the class JwtAuthenticationServiceImplTest method anonymousUserToken.

@Test
public void anonymousUserToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    String token = getToken(webClient);
    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 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 72 with JwtClaims

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

the class OpenIDConnectAuthenticator method isExpired.

@Override
public boolean isExpired(Map<String, Object> config) {
    String idToken = (String) config.get(OIDC_ID_TOKEN);
    if (idToken == null) {
        return true;
    } else {
        JsonWebSignature jws = new JsonWebSignature();
        try {
            jws.setCompactSerialization(idToken);
            // we don't care if its valid or not cryptographicly as the only way to verify is to
            // query
            // the remote identity provider's configuration url which is the same chanel as the
            // token
            // request.  If there is a malicious proxy there's no way for the client to know.
            // Also,
            // the client doesn't need to trust the, token, only bear it to the server which
            // will verify
            // it.
            String jwt = jws.getUnverifiedPayload();
            JwtClaims claims = JwtClaims.parse(jwt);
            // expired now is >= expiration AND exp is present
            return claims.getExpirationTime() == null || NumericDate.now().isOnOrAfter(claims.getExpirationTime());
        } catch (JoseException | InvalidJwtException | MalformedClaimException e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException)

Example 73 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project kylo by Teradata.

the class JwtRememberMeServices method encodeCookie.

/**
 * Encodes the specified tokens into a JWT cookie.
 *
 * <p>The first element of {@code tokens} should be the user's principal. The remaining elements are the groups assigned to the user.</p>
 *
 * @param tokens an array with the username and group names
 * @return a JWT cookie
 * @throws IllegalStateException if the secret key is invalid
 */
@Nonnull
@Override
protected String encodeCookie(@Nonnull final String[] tokens) {
    // Determine expiration time
    final NumericDate expireTime = NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis());
    expireTime.addSeconds(getExpirationTimeSeconds());
    // Build the JSON Web Token
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTime(expireTime);
    claims.setSubject(tokens[0]);
    claims.setStringListClaim(PRINCIPALS, Arrays.asList(tokens).subList(1, tokens.length));
    // Generate a signature
    final JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(algorithmIdentifier);
    jws.setKey(getSecretKey());
    jws.setKeyIdHeaderValue(getSecretKey().getAlgorithm());
    jws.setPayload(claims.toJson());
    // Serialize the cookie
    try {
        return jws.getCompactSerialization();
    } catch (final JoseException e) {
        log.error("Unable to encode cookie: ", e);
        throw new IllegalStateException("Unable to encode cookie: ", e);
    }
}
Also used : NumericDate(org.jose4j.jwt.NumericDate) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException) Nonnull(javax.annotation.Nonnull)

Example 74 with JwtClaims

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

the class JwtAuthenticationToken method create.

public static Authentication create(StaplerRequest request) {
    JwtClaims claims = validate(request);
    String subject = null;
    try {
        subject = claims.getSubject();
        if (subject.equals("anonymous")) {
            //if anonymous, we don't look in user db
            return Jenkins.getInstance().ANONYMOUS;
        } else {
            return new JwtAuthenticationToken(subject);
        }
    } catch (MalformedClaimException e) {
        logger.error(String.format("Error reading sub header for token %s", claims.getRawJson()), e);
        throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
    }
}
Also used : MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JwtClaims(org.jose4j.jwt.JwtClaims)

Example 75 with JwtClaims

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

the class JwtImplTest method getToken.

@Test
public void getToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User user = j.jenkins.getUser("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient.login("alice");
    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;
    System.out.println(token);
    System.out.println(jsw.toString());
    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());
    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

JwtClaims (org.jose4j.jwt.JwtClaims)130 Test (org.junit.Test)47 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)23 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)23 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)21 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)19 JoseException (org.jose4j.lang.JoseException)17 lombok.val (lombok.val)15 JsonWebSignature (org.jose4j.jws.JsonWebSignature)15 Map (java.util.Map)14 JwtContext (org.jose4j.jwt.consumer.JwtContext)11 NumericDate (org.jose4j.jwt.NumericDate)9 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)9 HashMap (java.util.HashMap)7 KeyStoreException (java.security.KeyStoreException)6 ArrayList (java.util.ArrayList)5 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)5 ExpiredTokenException (com.networknt.exception.ExpiredTokenException)4 JwksVerificationKeyResolver (org.jose4j.keys.resolvers.JwksVerificationKeyResolver)4 Test (org.junit.jupiter.api.Test)4