Search in sources :

Example 21 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)

Example 22 with JwtClaims

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

the class JwtHelper method verifyJwt.

/**
 * Verify JWT token signature as well as expiry.
 *
 * @param jwt String of Json web token
 * @return JwtClaims object
 * @throws InvalidJwtException InvalidJwtException
 * @throws ExpiredTokenException ExpiredTokenException
 */
public static JwtClaims verifyJwt(String jwt) throws InvalidJwtException, ExpiredTokenException {
    JwtClaims claims;
    if (Boolean.TRUE.equals(enableJwtCache)) {
        claims = cache.getIfPresent(jwt);
        if (claims != null) {
            try {
                // and it will never expired here. However, we need to handle other clients.
                if ((NumericDate.now().getValue() - secondsOfAllowedClockSkew) >= claims.getExpirationTime().getValue()) {
                    logger.info("Cached jwt token is expired!");
                    throw new ExpiredTokenException("Token is expired");
                }
            } catch (MalformedClaimException e) {
                // This is cached token and it is impossible to have this exception
                logger.error("MalformedClaimException:", e);
            }
            return claims;
        }
    }
    JwtConsumer consumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
    JwtContext jwtContext = consumer.process(jwt);
    JwtClaims jwtClaims = jwtContext.getJwtClaims();
    JsonWebStructure structure = jwtContext.getJoseObjects().get(0);
    String kid = structure.getKeyIdHeaderValue();
    // so we do expiration check here manually as we have the claim already for kid
    try {
        if ((NumericDate.now().getValue() - secondsOfAllowedClockSkew) >= jwtClaims.getExpirationTime().getValue()) {
            logger.info("jwt token is expired!");
            throw new ExpiredTokenException("Token is expired");
        }
    } catch (MalformedClaimException e) {
        logger.error("MalformedClaimException:", e);
        throw new InvalidJwtException("MalformedClaimException", new ErrorCodeValidator.Error(ErrorCodes.MALFORMED_CLAIM, "Invalid ExpirationTime Format"), e, jwtContext);
    }
    // get the public key certificate from the cache that is loaded from security.yml if it is not there,
    // go to OAuth2 server /oauth2/key endpoint to get the public key certificate with kid as parameter.
    X509Certificate certificate = certMap == null ? null : certMap.get(kid);
    if (certificate == null) {
        certificate = getCertFromOauth(kid);
        // null if bootstrapFromKeyService is true
        if (certMap == null)
            certMap = new HashMap<>();
        certMap.put(kid, certificate);
    }
    X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certificate);
    x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true);
    consumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(secondsOfAllowedClockSkew).setSkipDefaultAudienceValidation().setVerificationKeyResolver(x509VerificationKeyResolver).build();
    // Validate the JWT and process it to the Claims
    jwtContext = consumer.process(jwt);
    claims = jwtContext.getJwtClaims();
    if (Boolean.TRUE.equals(enableJwtCache)) {
        cache.put(jwt, claims);
    }
    return claims;
}
Also used : ExpiredTokenException(com.networknt.exception.ExpiredTokenException) JwtClaims(org.jose4j.jwt.JwtClaims) HashMap(java.util.HashMap) X509Certificate(java.security.cert.X509Certificate) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) X509VerificationKeyResolver(org.jose4j.keys.resolvers.X509VerificationKeyResolver) JsonWebStructure(org.jose4j.jwx.JsonWebStructure)

Example 23 with JwtClaims

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

Example 24 with JwtClaims

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

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

the class LightProxyHandler method handleRequest.

@Override
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
    if (config.isForwardJwtClaims()) {
        HeaderMap headerValues = httpServerExchange.getRequestHeaders();
        JwtClaims jwtClaims = extractClaimsFromJwt(headerValues);
        httpServerExchange.getRequestHeaders().put(HttpString.tryFromString(CLAIMS_KEY), new ObjectMapper().writeValueAsString(jwtClaims.getClaimsMap()));
    }
    proxyHandler.handleRequest(httpServerExchange);
}
Also used : HeaderMap(io.undertow.util.HeaderMap) JwtClaims(org.jose4j.jwt.JwtClaims) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

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