use of org.jose4j.jwt.consumer.JwtContext 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.jwt.consumer.JwtContext in project light-4j by networknt.
the class Http2ClientIT method isTokenExpired.
private static boolean isTokenExpired(String authorization) {
boolean expired = false;
String jwt = getJwtFromAuthorization(authorization);
if (jwt != null) {
try {
JwtConsumer consumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
JwtContext jwtContext = consumer.process(jwt);
JwtClaims jwtClaims = jwtContext.getJwtClaims();
try {
if ((NumericDate.now().getValue() - 60) >= jwtClaims.getExpirationTime().getValue()) {
expired = true;
}
} catch (MalformedClaimException e) {
logger.error("MalformedClaimException:", e);
}
} catch (InvalidJwtException e) {
e.printStackTrace();
}
}
return expired;
}
use of org.jose4j.jwt.consumer.JwtContext in project wildfly-swarm by wildfly-swarm.
the class DefaultJWTCallerPrincipalFactory method parse.
@Override
public JWTCallerPrincipal parse(final String token, final JWTAuthContextInfo authContextInfo) throws ParseException {
JWTCallerPrincipal principal = null;
try {
JwtConsumerBuilder builder = new JwtConsumerBuilder().setRequireExpirationTime().setRequireSubject().setSkipDefaultAudienceValidation().setExpectedIssuer(authContextInfo.getIssuedBy()).setVerificationKey(authContextInfo.getSignerKey()).setJwsAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256));
if (authContextInfo.getExpGracePeriodSecs() > 0) {
builder.setAllowedClockSkewInSeconds(authContextInfo.getExpGracePeriodSecs());
} else {
builder.setEvaluationTime(NumericDate.fromSeconds(0));
}
JwtConsumer jwtConsumer = builder.build();
JwtContext jwtContext = jwtConsumer.process(token);
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 DefaultJWTCallerPrincipal(token, type, claimsSet, principalName);
} catch (InvalidJwtException e) {
throw new ParseException("Failed to verify token", e);
} catch (MalformedClaimException e) {
throw new ParseException("Failed to verify token claims", e);
}
return principal;
}
use of org.jose4j.jwt.consumer.JwtContext 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;
}
}
use of org.jose4j.jwt.consumer.JwtContext 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;
}
Aggregations