use of org.jose4j.jwt.consumer.JwtConsumer 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.JwtConsumer 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;
}
use of org.jose4j.jwt.consumer.JwtConsumer in project blueocean-plugin by jenkinsci.
the class JwtAuthenticationServiceImplTest method getJwks.
@Test
public void getJwks() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
JenkinsRule.WebClient webClient = j.createWebClient();
User user = User.get("alice");
user.setFullName("Alice Cooper");
user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
webClient.login("alice");
// this call triggers the creation of a RSA key in RSAConfidentialKey::getPrivateKey
String token = getToken(webClient);
String jwksPayload = webClient.goTo("jwt-auth/jwk-set", "application/json").getWebResponse().getContentAsString();
System.out.println(jwksPayload);
JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwksPayload);
JwksVerificationKeyResolver jwksResolver = new JwksVerificationKeyResolver(jsonWebKeySet.getJsonWebKeys());
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
30).setRequireSubject().setVerificationKeyResolver(// verify the sign with the public key
jwksResolver).build();
JwtClaims claims = jwtConsumer.processToClaims(token);
Assert.assertEquals("alice", claims.getSubject());
Map<String, Object> claimMap = claims.getClaimsMap();
Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
Map<String, String> userContext = (Map<String, String>) context.get("user");
Assert.assertEquals("alice", userContext.get("id"));
Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
use of org.jose4j.jwt.consumer.JwtConsumer 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());
}
}
use of org.jose4j.jwt.consumer.JwtConsumer in project blueocean-plugin by jenkinsci.
the class JwtAuthenticationServiceImplTest method getToken.
@Test
public void getToken() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
User user = User.get("alice");
user.setFullName("Alice Cooper");
user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
JenkinsRule.WebClient webClient = j.createWebClient();
webClient.login("alice");
String token = getToken(webClient);
Assert.assertNotNull(token);
JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
System.out.println(token);
System.out.println(jsw);
String kid = jsw.getHeader("kid");
Assert.assertNotNull(kid);
Page page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
// for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
// System.out.println(valuePair);
// }
JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
System.out.println(jsonObject.toString());
RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
30).setRequireSubject().setVerificationKey(// verify the sign with the public key
rsaJsonWebKey.getKey()).build();
JwtClaims claims = jwtConsumer.processToClaims(token);
Assert.assertEquals("alice", claims.getSubject());
Map<String, Object> claimMap = claims.getClaimsMap();
Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
Map<String, String> userContext = (Map<String, String>) context.get("user");
Assert.assertEquals("alice", userContext.get("id"));
Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Aggregations