/** * Construct a default JwtClaims * @param expiresIn expires in * @return JwtClaims */ public static JwtClaims getJwtClaimsWithExpiresIn(int expiresIn) { JwtClaims claims = new JwtClaims(); claims.setIssuer(jwtConfig.getIssuer()); claims.setAudience(jwtConfig.getAudience()); claims.setExpirationTimeMinutesInTheFuture(expiresIn/60); claims.setGeneratedJwtId(); // a unique identifier for the token claims.setIssuedAtToNow(); // when the token was issued/created (now) claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago) claims.setClaim("version", jwtConfig.getVersion()); return claims; }
jws.setPayload(claims.toJson());
String nonce = claims.getStringClaimValue("nonce"); if (nonce == null) { logger.info("Rejected OpenID token without nonce."); String username = claims.getStringClaimValue(usernameClaim); if (username != null) return username;
public JwtClaims mockClaims() { JwtClaims claims = JwtIssuer.getDefaultJwtClaims(); claims.setClaim("user_id", "steve"); claims.setClaim("user_type", "EMPLOYEE"); claims.setClaim("client_id", "aaaaaaaa-1234-1234-1234-bbbbbbbb"); List<String> scope = Arrays.asList("api.r", "api.w"); claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array return claims; } }
@Override public void setUser(DemoiselleUser user, String issuer, String audience) { long time = (org.jose4j.jwt.NumericDate.now().getValueInMillis() + (config.getTimetoLiveMilliseconds())); try { JwtClaims claims = new JwtClaims(); claims.setIssuer(issuer != null ? issuer : config.getIssuer()); claims.setExpirationTime(org.jose4j.jwt.NumericDate.fromMilliseconds(time)); claims.setAudience(audience != null ? audience : config.getAudience()); claims.setGeneratedJwtId(); claims.setIssuedAtToNow(); claims.setNotBeforeMinutesInThePast(1); claims.setClaim("identity", (user.getIdentity())); claims.setClaim("name", (user.getName())); claims.setClaim("roles", (user.getRoles())); claims.setClaim("permissions", (user.getPermissions())); claims.setClaim("params", (user.getParams())); JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKey(privateKey); jws.setKeyIdHeaderValue("demoiselle-security-jwt"); jws.setAlgorithmHeaderValue(config.getAlgorithmIdentifiers()); token.setKey(jws.getCompactSerialization()); token.setType(TokenType.JWT); } catch (JoseException ex) { throw new DemoiselleSecurityException(bundle.general(), Response.Status.UNAUTHORIZED.getStatusCode(), ex); } }
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; }
@Override public String createToken(final String to) { try { val token = UUID.randomUUID().toString(); val claims = new JwtClaims(); claims.setJwtId(token); claims.setIssuer(issuer); claims.setAudience(issuer); claims.setExpirationTimeMinutesInTheFuture(properties.getReset().getExpirationMinutes()); claims.setIssuedAtToNow(); val holder = ClientInfoHolder.getClientInfo(); if (holder != null) { claims.setStringClaim("origin", holder.getServerIpAddress()); claims.setStringClaim("client", holder.getClientIpAddress()); } claims.setSubject(to); LOGGER.debug("Creating password management token for [{}]", to); val json = claims.toJson(); LOGGER.debug("Encoding the generated JSON token..."); return this.cipherExecutor.encode(json); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
JwtClaims claims = new JwtClaims(); claims.setIssuer(issuer); claims.setIssuedAt(NumericDate.fromMilliseconds(issuedAtDate.getTime())); claims.setExpirationTime(NumericDate.fromMilliseconds(expiresOnDate.getTime())); claims.setSubject(userId.toCompactId()); claims.setClaim("sId", scopeId.toCompactId()); jws.setPayload(claims.toJson()); jws.setKey(CertificateUtils.stringToPrivateKey(certificate.getPrivateKey(), certificate.getPassword())); jwt = jws.getCompactSerialization();
@Override public String createToken(HobsonUser user) { try { JwtClaims claims = new JwtClaims(); claims.setIssuer(oidcConfig.getIssuer()); claims.setAudience(System.getenv("OIDC_AUDIENCE") != null ? System.getenv("OIDC_AUDIENCE") : System.getProperty("OIDC_AUDIENCE", "hobson-webconsole")); claims.setSubject(user.getId()); claims.setStringClaim(PROP_FIRST_NAME, user.getGivenName()); claims.setStringClaim(PROP_LAST_NAME, user.getFamilyName()); claims.setExpirationTimeMinutesInTheFuture(DEFAULT_EXPIRATION_MINUTES); claims.setClaim("realm_access", Collections.singletonMap("roles", user.getRoles())); Collection<String> hubs = getHubsForUser(user.getId()); if (hubs != null) { claims.setStringClaim("hubs", StringUtils.join(hubs, ",")); } JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKey(((RsaJsonWebKey)oidcConfig.getSigningKey()).getPrivateKey()); jws.setKeyIdHeaderValue(((RsaJsonWebKey)oidcConfig.getSigningKey()).getKeyType()); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); return jws.getCompactSerialization(); } catch (JoseException e) { logger.error("Error generating token", e); throw new HobsonAuthenticationException("Error generating token"); } }
public String generateToken(String subject) { final JwtClaims claims = new JwtClaims(); claims.setSubject(subject); claims.setExpirationTimeMinutesInTheFuture(TOKEN_EXPIRATION_IN_MINUTES); final JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setAlgorithmHeaderValue(HMAC_SHA256); jws.setKey(new HmacKey(tokenSecret)); jws.setDoKeyValidation(false); //relaxes hmac key length restrictions try { return jws.getCompactSerialization(); } catch (JoseException e) { throw new RuntimeException(e); } }
@NotNull public static String createToken(@NotNull JsonWebEncryption jwe, @NotNull User user, @NotNull NumericDate expireAt) { try { JwtClaims claims = new JwtClaims(); claims.setExpirationTime(expireAt); claims.setGeneratedJwtId(); // a unique identifier for the token claims.setIssuedAtToNow(); // when the token was issued/created (now) claims.setNotBeforeMinutesInThePast(0.5f); // time before which the token is not yet valid (30 seconds ago) if (!user.isAnonymous()) { claims.setSubject(user.getUserName()); // the subject/principal is whom the token is about setClaim(claims, "email", user.getEmail()); setClaim(claims, "name", user.getRealName()); setClaim(claims, "external", user.getExternalId()); } jwe.setPayload(claims.toJson()); return jwe.getCompactSerialization(); } catch (JoseException e) { throw new IllegalStateException(e); } }
val claims = new JwtClaims(); claims.setJwtId(UUID.randomUUID().toString()); claims.setIssuer(casProperties.getAuthn().getUma().getIssuer()); claims.setAudience(String.valueOf(permissionTicket.getResourceSet().getId())); claims.setExpirationTime(expirationDate); claims.setIssuedAtToNow(); claims.setSubject(profile.getId()); permissionTicket.getClaims().forEach((k, v) -> claims.setStringListClaim(k, v.toString())); claims.setStringListClaim(OAuth20Constants.SCOPE, new ArrayList<>(permissionTicket.getScopes())); claims.setStringListClaim(OAuth20Constants.CLIENT_ID, service.getClientId());
private void replaceNumber(String name) { try { Number number = claimsSet.getClaimValue(name, Number.class); JsonNumber jsonNumber = (JsonNumber) wrapValue(number); claimsSet.setClaim(name, jsonNumber); } catch (MalformedClaimException e) { logger.warn("replaceNumber failure for: " + name, e); } } }
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);
try { val json = this.cipherExecutor.decode(token); val claims = JwtClaims.parse(json); if (!claims.getIssuer().equals(issuer)) { LOGGER.error("Token issuer does not match CAS"); return null; if (claims.getAudience().isEmpty() || !claims.getAudience().get(0).equals(issuer)) { LOGGER.error("Token audience does not match CAS"); return null; if (StringUtils.isBlank(claims.getSubject())) { LOGGER.error("Token has no subject identifier"); return null; if (!claims.getStringClaimValue("origin").equals(holder.getServerIpAddress())) { LOGGER.error("Token origin server IP address does not match CAS"); return null; if (!claims.getStringClaimValue("client").equals(holder.getClientIpAddress())) { LOGGER.error("Token client IP address does not match CAS"); return null; val expirationTime = claims.getExpirationTime(); if (expirationTime.isBefore(NumericDate.now())) { LOGGER.error("Token has expired."); return claims.getSubject();
@Override public HobsonUser authenticate(String token) throws HobsonAuthenticationException { try { // extract the claims from the token JwtClaims claims = jwtConsumer.processToClaims(token); // make sure the token hasn't expired if (claims.getExpirationTime().isAfter(NumericDate.now())) { List<String> roles = null; Map realmAccess = claims.getClaimValue("realm_access", Map.class); if (realmAccess != null && realmAccess.containsKey("roles")) { roles = (List<String>)realmAccess.get("roles"); } return new HobsonUser.Builder(claims.getSubject()) .givenName(claims.getStringClaimValue(PROP_FIRST_NAME)) .familyName(claims.getStringClaimValue(PROP_LAST_NAME)) .roles(roles != null ? roles : new ArrayList<String>()) .hubs(Collections.singletonList(claims.getClaimValue("hubs", String.class))) .build(); } else { throw new HobsonAuthenticationException("Token has expired"); } } catch (Exception e) { throw new HobsonAuthenticationException("Error validating bearer token: " + e.getMessage()); } }
@Nullable public static User parseToken(@NotNull JsonWebEncryption jwe, @NotNull String token, int tokenEnsureTime) { try { jwe.setCompactSerialization(token); final JwtClaims claims = JwtClaims.parse(jwe.getPayload()); final NumericDate now = NumericDate.now(); final NumericDate expire = NumericDate.fromMilliseconds(now.getValueInMillis()); if (tokenEnsureTime > 0) { expire.addSeconds(tokenEnsureTime); } if (claims.getExpirationTime() == null || claims.getExpirationTime().isBefore(expire)) { return null; } if (claims.getNotBefore() == null || claims.getNotBefore().isAfter(now)) { return null; } if (claims.getSubject() == null) { return User.getAnonymous(); } return User.create( claims.getSubject(), claims.getClaimValue("name", String.class), claims.getClaimValue("email", String.class), claims.getClaimValue("external", String.class) ); } catch (JoseException | MalformedClaimException | InvalidJwtException e) { log.warn("Token parsing error: " + e.getMessage()); return null; } }
public String getSubject() throws MalformedClaimException { return getClaimValue(ReservedClaimNames.SUBJECT, String.class); }
@Override public Set<String> getAudience() { final Set<String> audSet = new HashSet<>(); try { final List<String> audList = claimsSet.getStringListClaimValue("aud"); if (audList != null) { audSet.addAll(audList); } } catch (final MalformedClaimException e) { try { final String aud = claimsSet.getStringClaimValue("aud"); audSet.add(aud); } catch (final MalformedClaimException e1) { logger.log(Level.FINEST, "Can't retrieve malformed 'aud' claim.", e); } } return audSet.isEmpty() ? null : audSet; }
JwtClaims claimsSet = jwtContext.getJwtClaims(); name = claimsSet.getClaimValue("upn", String.class); if (name == null) { name = claimsSet.getClaimValue("preferred_username", String.class); if (name == null) { name = claimsSet.getSubject();