Search in sources :

Example 11 with JwtClaims

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

use of org.jose4j.jwt.JwtClaims in project kafka by apache.

the class ValidatorAccessTokenValidator method validate.

/**
 * Accepts an OAuth JWT access token in base-64 encoded format, validates, and returns an
 * OAuthBearerToken.
 *
 * @param accessToken Non-<code>null</code> JWT access token
 * @return {@link OAuthBearerToken}
 * @throws ValidateException Thrown on errors performing validation of given token
 */
@SuppressWarnings("unchecked")
public OAuthBearerToken validate(String accessToken) throws ValidateException {
    SerializedJwt serializedJwt = new SerializedJwt(accessToken);
    JwtContext jwt;
    try {
        jwt = jwtConsumer.process(serializedJwt.getToken());
    } catch (InvalidJwtException e) {
        throw new ValidateException(String.format("Could not validate the access token: %s", e.getMessage()), e);
    }
    JwtClaims claims = jwt.getJwtClaims();
    Object scopeRaw = getClaim(() -> claims.getClaimValue(scopeClaimName), scopeClaimName);
    Collection<String> scopeRawCollection;
    if (scopeRaw instanceof String)
        scopeRawCollection = Collections.singletonList((String) scopeRaw);
    else if (scopeRaw instanceof Collection)
        scopeRawCollection = (Collection<String>) scopeRaw;
    else
        scopeRawCollection = Collections.emptySet();
    NumericDate expirationRaw = getClaim(claims::getExpirationTime, ReservedClaimNames.EXPIRATION_TIME);
    String subRaw = getClaim(() -> claims.getStringClaimValue(subClaimName), subClaimName);
    NumericDate issuedAtRaw = getClaim(claims::getIssuedAt, ReservedClaimNames.ISSUED_AT);
    Set<String> scopes = ClaimValidationUtils.validateScopes(scopeClaimName, scopeRawCollection);
    long expiration = ClaimValidationUtils.validateExpiration(ReservedClaimNames.EXPIRATION_TIME, expirationRaw != null ? expirationRaw.getValueInMillis() : null);
    String sub = ClaimValidationUtils.validateSubject(subClaimName, subRaw);
    Long issuedAt = ClaimValidationUtils.validateIssuedAt(ReservedClaimNames.ISSUED_AT, issuedAtRaw != null ? issuedAtRaw.getValueInMillis() : null);
    OAuthBearerToken token = new BasicOAuthBearerToken(accessToken, scopes, expiration, sub, issuedAt);
    return token;
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) JwtContext(org.jose4j.jwt.consumer.JwtContext) OAuthBearerToken(org.apache.kafka.common.security.oauthbearer.OAuthBearerToken) Collection(java.util.Collection)

Example 13 with JwtClaims

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

use of org.jose4j.jwt.JwtClaims in project cas by apereo.

the class BasePasswordManagementService method createToken.

@Override
public String createToken(final PasswordManagementQuery query) {
    try {
        val token = UUID.randomUUID().toString();
        val claims = new JwtClaims();
        val resetProperties = properties.getReset();
        claims.setJwtId(token);
        claims.setIssuer(issuer);
        claims.setAudience(issuer);
        val minutes = Beans.newDuration(resetProperties.getExpiration()).toMinutes();
        claims.setExpirationTimeMinutesInTheFuture((float) minutes);
        claims.setIssuedAtToNow();
        val holder = ClientInfoHolder.getClientInfo();
        if (holder != null) {
            if (resetProperties.isIncludeServerIpAddress()) {
                claims.setStringClaim("origin", holder.getServerIpAddress());
            }
            if (resetProperties.isIncludeClientIpAddress()) {
                claims.setStringClaim("client", holder.getClientIpAddress());
            }
        }
        claims.setSubject(query.getUsername());
        LOGGER.debug("Creating password management token for [{}]", query.getUsername());
        val json = claims.toJson();
        LOGGER.debug("Encoding the generated JSON token...");
        return this.cipherExecutor.encode(json);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return null;
}
Also used : lombok.val(lombok.val) JwtClaims(org.jose4j.jwt.JwtClaims)

Example 15 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project cas by apereo.

the class AccepttoApiUtils method buildAuthorizationHeaderPayloadForAuthentication.

private static String buildAuthorizationHeaderPayloadForAuthentication(final AccepttoMultifactorAuthenticationProperties acceptto) {
    val claims = new JwtClaims();
    claims.setClaim("uid", acceptto.getOrganizationId());
    claims.setExpirationTimeMinutesInTheFuture(1);
    val payload = claims.toJson();
    LOGGER.trace("Authorization payload is [{}]", payload);
    val signingKey = new AesKey(acceptto.getOrganizationSecret().getBytes(StandardCharsets.UTF_8));
    LOGGER.trace("Signing authorization payload...");
    val signedBytes = EncodingUtils.signJwsHMACSha256(signingKey, payload.getBytes(StandardCharsets.UTF_8), Map.of());
    val authzPayload = new String(signedBytes, StandardCharsets.UTF_8);
    LOGGER.trace("Signed authorization payload is [{}]", authzPayload);
    return authzPayload;
}
Also used : lombok.val(lombok.val) JwtClaims(org.jose4j.jwt.JwtClaims) AesKey(org.jose4j.keys.AesKey)

Aggregations

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