Search in sources :

Example 11 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project kylo by Teradata.

the class JwtRememberMeServices method decodeCookie.

/**
 * Decodes the specified JWT cookie into tokens.
 *
 * <p>The first element of the return value with be the JWT subject. The remaining element (should be 1) is the principals JSON token.</p>
 *
 * @param cookie the JWT cookie
 * @return an array with the username and group names
 * @throws IllegalStateException  if the secret key is invalid
 * @throws InvalidCookieException if the cookie cannot be decoded
 */
@Nonnull
@Override
protected String[] decodeCookie(@Nonnull final String cookie) throws InvalidCookieException {
    // Build the JWT parser
    final JwtConsumer consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis())).setVerificationKey(getSecretKey()).build();
    // Parse the cookie
    final String user;
    final List<String> principalsClaim;
    try {
        final JwtClaims claims = consumer.processToClaims(cookie);
        user = claims.getSubject();
        principalsClaim = claims.getStringListClaimValue(PRINCIPALS);
    } catch (final InvalidJwtException e) {
        log.debug("JWT cookie is invalid: ", e);
        throw new InvalidCookieException("JWT cookie is invalid: " + e);
    } catch (final MalformedClaimException e) {
        log.debug("JWT cookie is malformed: ", e);
        throw new InvalidCookieException("JWT cookie is malformed: " + cookie);
    }
    if (StringUtils.isBlank(user)) {
        throw new InvalidCookieException("Missing user in JWT cookie: " + cookie);
    }
    // Build the token array
    final Stream<String> userStream = Stream.of(user);
    final Stream<String> groupStream = principalsClaim.stream();
    return Stream.concat(userStream, groupStream).toArray(String[]::new);
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) Nonnull(javax.annotation.Nonnull)

Example 12 with JwtConsumer

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

the class BoxDeveloperEditionAPIConnectionTest method getClaimsFromRequest.

private JwtClaims getClaimsFromRequest(Request request) throws Exception {
    // Get the JWT out of the request body
    String body = request.getBodyAsString();
    String[] tokens = body.split("&");
    String jwt = null;
    for (String s : tokens) {
        String[] parts = s.split("=");
        if (parts[0] != null && parts[0].equals("assertion") && parts[1] != null) {
            jwt = parts[1];
        }
    }
    if (jwt == null) {
        throw new Exception("No jwt assertion found in request body");
    }
    // Parse out the JWT to verify the claims
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setSkipSignatureVerification().setSkipAllValidators().build();
    return jwtConsumer.processToClaims(jwt);
}
Also used : JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer)

Example 13 with JwtConsumer

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

Example 14 with JwtConsumer

use of org.jose4j.jwt.consumer.JwtConsumer in project stdlib by petergeneric.

the class JwtCreationRestServiceImpl method getResult.

@Override
public String getResult(String token, final String secret, final String payload, final String op) {
    final TemplateCall template = templater.template(PREFIX + "jwt_generated.html");
    final Long expireTime;
    if (token == null) {
        try {
            JwtClaims claims = JwtClaims.parse(payload);
            if (claims.getExpirationTime() != null)
                expireTime = claims.getExpirationTime().getValueInMillis();
            else
                expireTime = null;
            token = createJWT(secret, payload);
        } catch (InvalidJwtException | MalformedClaimException | JoseException e) {
            throw new RuntimeException(e);
        }
    } else {
        // User has provided a JWT. We should simply parse it and extract the expiry time (for the cookie)
        try {
            JwtConsumer jwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
            final JwtClaims claims = jwtConsumer.processToClaims(token);
            if (claims.getExpirationTime() != null)
                expireTime = claims.getExpirationTime().getValueInMillis();
            else
                expireTime = null;
        } catch (InvalidJwtException | MalformedClaimException e) {
            throw new RuntimeException(e);
        }
    }
    final boolean save = StringUtils.equalsIgnoreCase("save", op);
    // Optionally save as a cookie
    if (save) {
        Cookie cookie = new Cookie(cookieName, token);
        // Set the cookie path based on the webapp endpoint path
        cookie.setPath(webappEndpoint.getPath());
        // If the webapp has an https endpoint (or if we were accessed by HTTPS) then set the cookie as a secure cookie
        cookie.setSecure(HttpCallContext.get().getRequest().isSecure() || StringUtils.equalsIgnoreCase("https", webappEndpoint.getScheme()));
        // Expire the cookie 1 minute before the token expires
        if (expireTime != null)
            cookie.setMaxAge(expireTime.intValue() - 60);
        // Kill the current session (just in case it's associated with a job manager login)
        final HttpSession session = HttpCallContext.get().getRequest().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        // Now add the JWT cookie
        HttpCallContext.get().getResponse().addCookie(cookie);
    }
    template.set("saved", save);
    template.set("token", token);
    return template.process();
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) Cookie(javax.servlet.http.Cookie) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) HttpSession(javax.servlet.http.HttpSession) TemplateCall(com.peterphi.std.guice.web.rest.templating.TemplateCall) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer)

Example 15 with JwtConsumer

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

the class Http2ClientTest 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)

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