Search in sources :

Example 1 with JoseException

use of org.jose4j.lang.JoseException in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationToken method validate.

private static JwtClaims validate(StaplerRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServiceException.UnauthorizedException("JWT token not found");
    }
    String token = authHeader.substring("Bearer ".length());
    try {
        JsonWebStructure jws = JsonWebStructure.fromCompactSerialization(token);
        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");
        }
        JwtToken.JwtRsaDigitalSignatureKey key = new JwtToken.JwtRsaDigitalSignatureKey(kid);
        try {
            if (!key.exists()) {
                throw new ServiceException.NotFoundException(String.format("kid %s not found", kid));
            }
        } catch (IOException e) {
            logger.error(String.format("Error reading RSA key for id %s: %s", kid, e.getMessage()), e);
            throw new ServiceException.UnexpectedErrorException("Unexpected error: " + e.getMessage(), e);
        }
        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
        key.getPublicKey()).build();
        try {
            JwtContext context = jwtConsumer.process(token);
            JwtClaims claims = context.getJwtClaims();
            //check if token expired
            NumericDate expirationTime = claims.getExpirationTime();
            if (expirationTime.isBefore(NumericDate.now())) {
                throw new ServiceException.UnauthorizedException("Invalid JWT token: expired");
            }
            return claims;
        } 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) 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) IOException(java.io.IOException) JwtToken(io.jenkins.blueocean.auth.jwt.JwtToken) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JsonWebStructure(org.jose4j.jwx.JsonWebStructure)

Example 2 with JoseException

use of org.jose4j.lang.JoseException in project kafka by apache.

the class RefreshingHttpsJwksVerificationKeyResolver method resolveKey.

@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException {
    if (!isInitialized)
        throw new IllegalStateException("Please call init() first");
    try {
        List<JsonWebKey> jwks = refreshingHttpsJwks.getJsonWebKeys();
        JsonWebKey jwk = verificationJwkSelector.select(jws, jwks);
        if (jwk != null)
            return jwk.getKey();
        String keyId = jws.getKeyIdHeaderValue();
        if (refreshingHttpsJwks.maybeExpediteRefresh(keyId))
            log.debug("Refreshing JWKs from {} as no suitable verification key for JWS w/ header {} was found in {}", refreshingHttpsJwks.getLocation(), jws.getHeaders().getFullHeaderAsJsonString(), jwks);
        StringBuilder sb = new StringBuilder();
        sb.append("Unable to find a suitable verification key for JWS w/ header ").append(jws.getHeaders().getFullHeaderAsJsonString());
        sb.append(" from JWKs ").append(jwks).append(" obtained from ").append(refreshingHttpsJwks.getLocation());
        throw new UnresolvableKeyException(sb.toString());
    } catch (JoseException | IOException e) {
        StringBuilder sb = new StringBuilder();
        sb.append("Unable to find a suitable verification key for JWS w/ header ").append(jws.getHeaders().getFullHeaderAsJsonString());
        sb.append(" due to an unexpected exception (").append(e).append(") while obtaining or using keys from JWKS endpoint at ").append(refreshingHttpsJwks.getLocation());
        throw new UnresolvableKeyException(sb.toString(), e);
    }
}
Also used : UnresolvableKeyException(org.jose4j.lang.UnresolvableKeyException) JoseException(org.jose4j.lang.JoseException) JsonWebKey(org.jose4j.jwk.JsonWebKey) IOException(java.io.IOException)

Example 3 with JoseException

use of org.jose4j.lang.JoseException in project kafka by apache.

the class JwksFileVerificationKeyResolver method init.

@Override
public void init() throws IOException {
    log.debug("Starting creation of new VerificationKeyResolver from {}", jwksFile);
    String json = Utils.readFileAsString(jwksFile.toFile().getPath());
    JsonWebKeySet jwks;
    try {
        jwks = new JsonWebKeySet(json);
    } catch (JoseException e) {
        throw new IOException(e);
    }
    delegate = new JwksVerificationKeyResolver(jwks.getJsonWebKeys());
}
Also used : JoseException(org.jose4j.lang.JoseException) IOException(java.io.IOException) JwksVerificationKeyResolver(org.jose4j.keys.resolvers.JwksVerificationKeyResolver) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet)

Example 4 with JoseException

use of org.jose4j.lang.JoseException in project tomee by apache.

the class PublicKeyResolver method parseJwks.

private Map<String, Key> parseJwks(final String publicKey) {
    final JsonObject jwks;
    try {
        jwks = Json.createReader(new StringReader(publicKey)).readObject();
    } catch (final JsonParsingException e) {
        return Collections.emptyMap();
    }
    try {
        final JsonArray keys = jwks.getJsonArray(JWK_SET_MEMBER_NAME);
        for (final JsonValue key : keys) {
            validateJwk(key.asJsonObject());
        }
    } catch (final Exception e) {
        throw new DeploymentException("MicroProfile Public Key JWKS invalid format.");
    }
    try {
        final JsonWebKeySet keySet = new JsonWebKeySet(publicKey);
        final Map<String, Key> keys = keySet.getJsonWebKeys().stream().collect(Collectors.toMap(JsonWebKey::getKeyId, JsonWebKey::getKey));
        return Collections.unmodifiableMap(keys);
    } catch (final JoseException e) {
        throw new DeploymentException(JWTAuthConfigurationProperties.PUBLIC_KEY_ERROR + " JWK.", e);
    }
}
Also used : JsonArray(javax.json.JsonArray) JoseException(org.jose4j.lang.JoseException) StringReader(java.io.StringReader) JsonValue(javax.json.JsonValue) JsonObject(javax.json.JsonObject) DeploymentException(javax.enterprise.inject.spi.DeploymentException) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) URISyntaxException(java.net.URISyntaxException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) IOException(java.io.IOException) JoseException(org.jose4j.lang.JoseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JsonParsingException(javax.json.stream.JsonParsingException) JsonWebKey(org.jose4j.jwk.JsonWebKey) Key(java.security.Key) JsonParsingException(javax.json.stream.JsonParsingException)

Example 5 with JoseException

use of org.jose4j.lang.JoseException in project tomee by apache.

the class PublicKeyResolver method parseJwk.

private Map<String, Key> parseJwk(final String publicKey) {
    final JsonObject jwk;
    try {
        jwk = Json.createReader(new StringReader(publicKey)).readObject();
    } catch (final JsonParsingException e) {
        return Collections.emptyMap();
    }
    if (jwk.containsKey(JWK_SET_MEMBER_NAME)) {
        return Collections.emptyMap();
    }
    validateJwk(jwk);
    try {
        final JsonWebKey key = JsonWebKey.Factory.newJwk(publicKey);
        return Collections.singletonMap(key.getKeyId(), key.getKey());
    } catch (final JoseException e) {
        throw new DeploymentException(JWTAuthConfigurationProperties.PUBLIC_KEY_ERROR + " JWK.", e);
    }
}
Also used : JoseException(org.jose4j.lang.JoseException) StringReader(java.io.StringReader) JsonWebKey(org.jose4j.jwk.JsonWebKey) JsonObject(javax.json.JsonObject) DeploymentException(javax.enterprise.inject.spi.DeploymentException) JsonParsingException(javax.json.stream.JsonParsingException)

Aggregations

JoseException (org.jose4j.lang.JoseException)17 JwtClaims (org.jose4j.jwt.JwtClaims)7 IOException (java.io.IOException)6 JsonWebKey (org.jose4j.jwk.JsonWebKey)6 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)5 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)5 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)4 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)4 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 NumericDate (org.jose4j.jwt.NumericDate)3 StringReader (java.io.StringReader)2 Map (java.util.Map)2 DeploymentException (javax.enterprise.inject.spi.DeploymentException)2 JsonObject (javax.json.JsonObject)2 JsonParsingException (javax.json.stream.JsonParsingException)2 JsonWebKeySet (org.jose4j.jwk.JsonWebKeySet)2 JwtContext (org.jose4j.jwt.consumer.JwtContext)2 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)2 TemplateCall (com.peterphi.std.guice.web.rest.templating.TemplateCall)1