use of org.jose4j.jwt.JwtClaims 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.JwtClaims 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"));
}
use of org.jose4j.jwt.JwtClaims in project java by kubernetes-client.
the class TestUtils method generateJWT.
/**
* Utility for generating JWTs
*
* @param uid Maps to the sub claim
* @param issuer URL of the issuer
* @param signing Private key to sign the JWT
* @param dos Determines at what time point the JWT should be generated
* @return
* @throws Exception
*/
public static String generateJWT(String uid, String issuer, PrivateKey signing, DateOptions dos) throws Exception {
JwtClaims claims = new JwtClaims();
claims.setIssuer(issuer);
ArrayList<String> audiences = new ArrayList<String>();
claims.setSubject(uid);
claims.setGeneratedJwtId();
// a unique identifier for the token
claims.setGeneratedJwtId();
if (dos == DateOptions.Now) {
// when the token was issued/created (now)
claims.setIssuedAtToNow();
claims.setNotBeforeMinutesInThePast(// time before which the token is not yet valid (2 minutes ago)
60000 / 1000 / 60);
claims.setExpirationTimeMinutesInTheFuture(// time before which the token is not yet valid (2 minutes ago)
60000 / 1000 / 60);
}
if (dos == DateOptions.Past) {
claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() - 120000L));
claims.setNotBeforeMinutesInThePast(// time before which the token is not yet valid (2 minutes ago)
4);
claims.setExpirationTimeMinutesInTheFuture(// time before which the token is not yet valid (2 minutes ago)
-1);
}
if (dos == DateOptions.Future) {
claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() + 120000L));
claims.setNotBeforeMinutesInThePast(// time before which the token is not yet valid (2 minutes ago)
-1);
claims.setExpirationTimeMinutesInTheFuture(// time before which the token is not yet valid (2 minutes ago)
4);
}
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(signing);
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
return jws.getCompactSerialization();
}
use of org.jose4j.jwt.JwtClaims in project box-java-sdk by box.
the class BoxDeveloperEditionAPIConnectionTest method getRequestMatcher.
private RequestMatcherExtension getRequestMatcher(final String tokenPath) {
return new RequestMatcherExtension() {
@Override
public MatchResult match(Request request, Parameters parameters) {
if (!request.getMethod().equals(RequestMethod.POST) || !request.getUrl().equals(tokenPath)) {
return MatchResult.noMatch();
}
Assert.assertNotNull("JTI should be saved from previous request", BoxDeveloperEditionAPIConnectionTest.this.jtiClaim);
try {
JwtClaims claims = BoxDeveloperEditionAPIConnectionTest.this.getClaimsFromRequest(request);
String jti = claims.getJwtId();
long expTimestamp = claims.getExpirationTime().getValue();
Assert.assertNotEquals("JWT should have a new timestamp", 1511003910L, expTimestamp);
Assert.assertNotEquals("JWT should have a new jti claim", BoxDeveloperEditionAPIConnectionTest.this.jtiClaim, jti);
} catch (Exception ex) {
Assert.fail("Could not parse JWT when request is retried: " + ex.getMessage());
}
return MatchResult.exactMatch();
}
};
}
use of org.jose4j.jwt.JwtClaims in project box-java-sdk by box.
the class BoxDeveloperEditionAPIConnection method constructJWTAssertion.
private String constructJWTAssertion(NumericDate now) {
JwtClaims claims = new JwtClaims();
claims.setIssuer(this.getClientID());
claims.setAudience(JWT_AUDIENCE);
if (now == null) {
claims.setExpirationTimeMinutesInTheFuture(0.5f);
} else {
now.addSeconds(30L);
claims.setExpirationTime(now);
}
claims.setSubject(this.entityID);
claims.setClaim("box_sub_type", this.entityType.toString());
claims.setGeneratedJwtId(64);
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(this.decryptPrivateKey());
jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
jws.setHeader("typ", "JWT");
if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
jws.setHeader("kid", this.publicKeyID);
}
String assertion;
try {
assertion = jws.getCompactSerialization();
} catch (JoseException e) {
throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
}
return assertion;
}
Aggregations