use of org.jose4j.jwt.JwtClaims in project blueocean-plugin by jenkinsci.
the class JwtAuthenticationServiceImplTest method anonymousUserToken.
@Test
public void anonymousUserToken() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
JenkinsRule.WebClient webClient = j.createWebClient();
String token = getToken(webClient);
Assert.assertNotNull(token);
JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
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());
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("anonymous", 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("anonymous", userContext.get("id"));
}
use of org.jose4j.jwt.JwtClaims in project java by kubernetes-client.
the class OpenIDConnectAuthenticator method isExpired.
@Override
public boolean isExpired(Map<String, Object> config) {
String idToken = (String) config.get(OIDC_ID_TOKEN);
if (idToken == null) {
return true;
} else {
JsonWebSignature jws = new JsonWebSignature();
try {
jws.setCompactSerialization(idToken);
// we don't care if its valid or not cryptographicly as the only way to verify is to
// query
// the remote identity provider's configuration url which is the same chanel as the
// token
// request. If there is a malicious proxy there's no way for the client to know.
// Also,
// the client doesn't need to trust the, token, only bear it to the server which
// will verify
// it.
String jwt = jws.getUnverifiedPayload();
JwtClaims claims = JwtClaims.parse(jwt);
// expired now is >= expiration AND exp is present
return claims.getExpirationTime() == null || NumericDate.now().isOnOrAfter(claims.getExpirationTime());
} catch (JoseException | InvalidJwtException | MalformedClaimException e) {
throw new RuntimeException(e);
}
}
}
use of org.jose4j.jwt.JwtClaims in project kylo by Teradata.
the class JwtRememberMeServices method encodeCookie.
/**
* Encodes the specified tokens into a JWT cookie.
*
* <p>The first element of {@code tokens} should be the user's principal. The remaining elements are the groups assigned to the user.</p>
*
* @param tokens an array with the username and group names
* @return a JWT cookie
* @throws IllegalStateException if the secret key is invalid
*/
@Nonnull
@Override
protected String encodeCookie(@Nonnull final String[] tokens) {
// Determine expiration time
final NumericDate expireTime = NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis());
expireTime.addSeconds(getExpirationTimeSeconds());
// Build the JSON Web Token
final JwtClaims claims = new JwtClaims();
claims.setExpirationTime(expireTime);
claims.setSubject(tokens[0]);
claims.setStringListClaim(PRINCIPALS, Arrays.asList(tokens).subList(1, tokens.length));
// Generate a signature
final JsonWebSignature jws = new JsonWebSignature();
jws.setAlgorithmHeaderValue(algorithmIdentifier);
jws.setKey(getSecretKey());
jws.setKeyIdHeaderValue(getSecretKey().getAlgorithm());
jws.setPayload(claims.toJson());
// Serialize the cookie
try {
return jws.getCompactSerialization();
} catch (final JoseException e) {
log.error("Unable to encode cookie: ", e);
throw new IllegalStateException("Unable to encode cookie: ", e);
}
}
use of org.jose4j.jwt.JwtClaims in project blueocean-plugin by jenkinsci.
the class JwtAuthenticationToken method create.
public static Authentication create(StaplerRequest request) {
JwtClaims claims = validate(request);
String subject = null;
try {
subject = claims.getSubject();
if (subject.equals("anonymous")) {
//if anonymous, we don't look in user db
return Jenkins.getInstance().ANONYMOUS;
} else {
return new JwtAuthenticationToken(subject);
}
} catch (MalformedClaimException e) {
logger.error(String.format("Error reading sub header for token %s", claims.getRawJson()), e);
throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
}
}
use of org.jose4j.jwt.JwtClaims in project blueocean-plugin by jenkinsci.
the class JwtImplTest method getToken.
@Test
public void getToken() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
User user = j.jenkins.getUser("alice");
user.setFullName("Alice Cooper");
user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
JenkinsRule.WebClient webClient = j.createWebClient();
webClient.login("alice");
Page page = webClient.goTo("jwt-auth/token/", null);
String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
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.toString());
String kid = jsw.getHeader("kid");
Assert.assertNotNull(kid);
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