Search in sources :

Example 6 with InvalidJwtException

use of org.jose4j.jwt.consumer.InvalidJwtException 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 7 with InvalidJwtException

use of org.jose4j.jwt.consumer.InvalidJwtException 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 8 with InvalidJwtException

use of org.jose4j.jwt.consumer.InvalidJwtException 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 9 with InvalidJwtException

use of org.jose4j.jwt.consumer.InvalidJwtException 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 10 with InvalidJwtException

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

Aggregations

InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)13 JwtClaims (org.jose4j.jwt.JwtClaims)12 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)11 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)10 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)9 JwtContext (org.jose4j.jwt.consumer.JwtContext)8 NumericDate (org.jose4j.jwt.NumericDate)3 JoseException (org.jose4j.lang.JoseException)3 ExpiredTokenException (com.networknt.exception.ExpiredTokenException)2 Status (com.networknt.status.Status)2 ServiceException (io.jenkins.blueocean.commons.ServiceException)2 HeaderMap (io.undertow.util.HeaderMap)2 Cookie (javax.servlet.http.Cookie)2 AlgorithmConstraints (org.jose4j.jwa.AlgorithmConstraints)2 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)2 Operation (com.networknt.oas.model.Operation)1 Path (com.networknt.oas.model.Path)1 SecurityParameter (com.networknt.oas.model.SecurityParameter)1 SecurityRequirement (com.networknt.oas.model.SecurityRequirement)1 TemplateCall (com.peterphi.std.guice.web.rest.templating.TemplateCall)1