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());
}
}
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);
}
}
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());
}
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);
}
}
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);
}
}
Aggregations