use of org.apache.tomee.microprofile.jwt.principal.JWTCallerPrincipal 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;
}
Aggregations