use of org.jose4j.jwt.consumer.JwtConsumer in project kylo by Teradata.
the class JwtRememberMeServices method decodeCookie.
/**
* Decodes the specified JWT cookie into tokens.
*
* <p>The first element of the return value with be the JWT subject. The remaining element (should be 1) is the principals JSON token.</p>
*
* @param cookie the JWT cookie
* @return an array with the username and group names
* @throws IllegalStateException if the secret key is invalid
* @throws InvalidCookieException if the cookie cannot be decoded
*/
@Nonnull
@Override
protected String[] decodeCookie(@Nonnull final String cookie) throws InvalidCookieException {
// Build the JWT parser
final JwtConsumer consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis())).setVerificationKey(getSecretKey()).build();
// Parse the cookie
final String user;
final List<String> principalsClaim;
try {
final JwtClaims claims = consumer.processToClaims(cookie);
user = claims.getSubject();
principalsClaim = claims.getStringListClaimValue(PRINCIPALS);
} catch (final InvalidJwtException e) {
log.debug("JWT cookie is invalid: ", e);
throw new InvalidCookieException("JWT cookie is invalid: " + e);
} catch (final MalformedClaimException e) {
log.debug("JWT cookie is malformed: ", e);
throw new InvalidCookieException("JWT cookie is malformed: " + cookie);
}
if (StringUtils.isBlank(user)) {
throw new InvalidCookieException("Missing user in JWT cookie: " + cookie);
}
// Build the token array
final Stream<String> userStream = Stream.of(user);
final Stream<String> groupStream = principalsClaim.stream();
return Stream.concat(userStream, groupStream).toArray(String[]::new);
}
use of org.jose4j.jwt.consumer.JwtConsumer in project box-java-sdk by box.
the class BoxDeveloperEditionAPIConnectionTest method getClaimsFromRequest.
private JwtClaims getClaimsFromRequest(Request request) throws Exception {
// Get the JWT out of the request body
String body = request.getBodyAsString();
String[] tokens = body.split("&");
String jwt = null;
for (String s : tokens) {
String[] parts = s.split("=");
if (parts[0] != null && parts[0].equals("assertion") && parts[1] != null) {
jwt = parts[1];
}
}
if (jwt == null) {
throw new Exception("No jwt assertion found in request body");
}
// Parse out the JWT to verify the claims
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setSkipSignatureVerification().setSkipAllValidators().build();
return jwtConsumer.processToClaims(jwt);
}
use of org.jose4j.jwt.consumer.JwtConsumer 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"));
}
use of org.jose4j.jwt.consumer.JwtConsumer in project stdlib by petergeneric.
the class JwtCreationRestServiceImpl method getResult.
@Override
public String getResult(String token, final String secret, final String payload, final String op) {
final TemplateCall template = templater.template(PREFIX + "jwt_generated.html");
final Long expireTime;
if (token == null) {
try {
JwtClaims claims = JwtClaims.parse(payload);
if (claims.getExpirationTime() != null)
expireTime = claims.getExpirationTime().getValueInMillis();
else
expireTime = null;
token = createJWT(secret, payload);
} catch (InvalidJwtException | MalformedClaimException | JoseException e) {
throw new RuntimeException(e);
}
} else {
// User has provided a JWT. We should simply parse it and extract the expiry time (for the cookie)
try {
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
final JwtClaims claims = jwtConsumer.processToClaims(token);
if (claims.getExpirationTime() != null)
expireTime = claims.getExpirationTime().getValueInMillis();
else
expireTime = null;
} catch (InvalidJwtException | MalformedClaimException e) {
throw new RuntimeException(e);
}
}
final boolean save = StringUtils.equalsIgnoreCase("save", op);
// Optionally save as a cookie
if (save) {
Cookie cookie = new Cookie(cookieName, token);
// Set the cookie path based on the webapp endpoint path
cookie.setPath(webappEndpoint.getPath());
// If the webapp has an https endpoint (or if we were accessed by HTTPS) then set the cookie as a secure cookie
cookie.setSecure(HttpCallContext.get().getRequest().isSecure() || StringUtils.equalsIgnoreCase("https", webappEndpoint.getScheme()));
// Expire the cookie 1 minute before the token expires
if (expireTime != null)
cookie.setMaxAge(expireTime.intValue() - 60);
// Kill the current session (just in case it's associated with a job manager login)
final HttpSession session = HttpCallContext.get().getRequest().getSession(false);
if (session != null) {
session.invalidate();
}
// Now add the JWT cookie
HttpCallContext.get().getResponse().addCookie(cookie);
}
template.set("saved", save);
template.set("token", token);
return template.process();
}
use of org.jose4j.jwt.consumer.JwtConsumer in project light-4j by networknt.
the class Http2ClientTest 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;
}
Aggregations