@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; } }