下面列出了怎么用io.jsonwebtoken.Jws的API类实例代码及写法,或者点击链接到github查看源代码。
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
}
if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
throw new IllegalArgumentException("Invalid Refresh Token scope");
}
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
SecurityUser securityUser = new SecurityUser();
securityUser.setUserPrincipal(principal);
return securityUser;
}
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
// The library representations of the JWT should be kept internal to this service.
try {
final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);
if (jws == null) {
throw new JwtException("Unable to parse token");
}
// Additional validation that subject is present
if (StringUtils.isEmpty(jws.getBody().getSubject())) {
throw new JwtException("No subject available in token");
}
// TODO: Validate issuer against active registry?
if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
throw new JwtException("No issuer available in token");
}
return jws.getBody().getSubject();
} catch (JwtException e) {
logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
final String errorMessage = "There was an error validating the JWT";
logger.error(errorMessage, e);
throw e;
}
}
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
}
if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
throw new IllegalArgumentException("Invalid Refresh Token scope");
}
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
securityUser.setUserPrincipal(principal);
return securityUser;
}
/**
* @param jwt, JWT issued by daming.
* @return claims that contains verified mobile and scope.
* @see #verify(String, String)
*/
@Deprecated
public SmsVerificationClaims verify(String jwt) {
if (jwt == null) {
throw new BadSmsVerificationJwtException("The jwt must not be null");
}
try {
JwtParser parser = Jwts.parser()
.setSigningKey(publicKey);
if (clock != null) {
parser = parser.setClock(clock);
}
Jws<Claims> claims = parser
.parseClaimsJws(jwt);
String mobile = claims.getBody().get("mobile", String.class);
String scope = claims.getBody().get("scope", String.class);
return new SmsVerificationClaims(mobile, scope);
} catch (Exception err) {
throw new BadSmsVerificationJwtException(err.getMessage(), err);
}
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey());
String orgId = jwsClaims.getBody().getSubject();
String tenantId = jwsClaims.getBody().get("tenant", String.class);
List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
List<GrantedAuthority> authorities = scopes.stream()
.map(authority -> new SimpleGrantedAuthority(authority))
.collect(Collectors.toList());
UserContext context = UserContext.create(tenantId, orgId, authorities);
return new JwtAuthenticationToken(context, context.getAuthorities());
}
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
// The library representations of the JWT should be kept internal to this service.
try {
final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);
if (jws == null) {
throw new JwtException("Unable to parse token");
}
// Additional validation that subject is present
if (StringUtils.isEmpty(jws.getBody().getSubject())) {
throw new JwtException("No subject available in token");
}
// TODO: Validate issuer against active IdentityProvider?
if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
throw new JwtException("No issuer available in token");
}
return jws.getBody().getSubject();
} catch (JwtException e) {
logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
final String errorMessage = "There was an error validating the JWT";
logger.error(errorMessage, e);
throw e;
}
}
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final String keyId = claims.get(KEY_ID_CLAIM, String.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
}
if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
throw new IllegalArgumentException("Invalid Refresh Token scope");
}
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME,
subject);
SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
securityUser.setUserPrincipal(principal);
return securityUser;
}
@SuppressWarnings("unchecked")
private Set<String> parseRoles(Jws<Claims> jwsClaim){
Set<String> roles = new HashSet<String>();
Map<String, Object> realmAccess =
(Map<String, Object>) jwsClaim.getBody().get("realm_access");
if (realmAccess != null) {
List<String> realmAccessRoles = (List<String>) realmAccess.get("roles");
if (realmAccessRoles != null) {
roles.addAll(realmAccessRoles);
}
}
Map<String, Object> resourceAccess =
(Map<String, Object>) jwsClaim.getBody().get("resource_access");
if (resourceAccess != null) {
Map<String, Object> elexisRcpOpenidAccess =
(Map<String, Object>) resourceAccess.get("elexis-rcp-openid");
if (elexisRcpOpenidAccess != null) {
List<String> elexisRcpOpenidAccessRoles =
(List<String>) elexisRcpOpenidAccess.get("roles");
if (elexisRcpOpenidAccessRoles != null) {
roles.addAll(elexisRcpOpenidAccessRoles);
}
}
}
return roles;
}
@Test
public void testRsa() throws Exception {
SSOConfig ssoConfig = SSOConfig.getInstance();
Key key = RsaKeyHelper.getRsaKey(new ClassPathResource(ssoConfig.getRsaJksStore()).getInputStream(),
ssoConfig.getRsaAlias(), ssoConfig.getRsaKeypass(), ssoConfig.getRsaStorepass());
Map<String, Object> claims = new HashMap<>();
claims.put("user", "cope");
Calendar expires = Calendar.getInstance();
expires.add(Calendar.HOUR, 2);
// 加密
String token = Jwts.builder()
.setClaims(claims)
.setSubject("test rsa jwt")
.setIssuedAt(new Date())
.setExpiration(expires.getTime())
.signWith(key, SignatureAlgorithm.RS512)
.compact();
System.out.println(token);
// CRT 证书中读取公钥解密
PublicKey publicKey = RsaKeyHelper.getRsaPublicKey(new ClassPathResource(ssoConfig.getRsaCertStore()).getInputStream());
Jws<Claims> crtClaimsJws = Jwts.parserBuilder().require("user", "cope")
.setSigningKey(publicKey).build().parseClaimsJws(token);
System.out.println("crt subject: " + crtClaimsJws.getBody().getSubject());
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static UserInfo getInfoFromToken(String token, PublicKey publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return new UserInfo(
ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
);
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static UserInfo getInfoFromToken(String token, byte[] publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return new UserInfo(
ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
);
}
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("JWT Token doesn't have any scopes");
}
SecurityUser securityUser = new SecurityUser();
securityUser.setEmail(subject);
securityUser.setAuthority(Authority.parse(scopes.get(0)));
securityUser.setEnabled(claims.get(ENABLED, Boolean.class));
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
securityUser.setUserPrincipal(principal);
String tenantId = claims.get(TENANT_ID, String.class);
if (tenantId != null) {
securityUser.setTenantId(1l);
}
String customerId = claims.get(CUSTOMER_ID, String.class);
if (customerId != null) {
securityUser.setCustomerId(1L);
}
return securityUser;
}
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) {
try {
return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() {
@Override
public Jws<String> onPlaintextJws(Jws<String> jws) {
return jws;
}
});
} catch (IllegalArgumentException iae) {
throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
}
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
log.info("=== refresh token ===");
validateRequestHeader(request);
String sRefreshToken = request.getHeader(ApplicationConstants.JwtInfo.HEADER_AUTHORIZATION);
sRefreshToken = sRefreshToken.substring(ApplicationConstants.JwtInfo.PREFIX_BEARER_TOKEN.length()).trim();
if (log.isDebugEnabled()) {
log.debug("refresh token:{}", sRefreshToken);
}
if (StringUtils.isBlank(sRefreshToken)) {
throw new BadCredentialsException("refresh token is blank.");
}
Jws<Claims> jwt = jwtBuilder.parseJwt(sRefreshToken);
if (jwt == null) {
log.error("failed to parse refresh token:{}", sRefreshToken);
throw new BadCredentialsException("bad refresh token.");
}
return attemptAuthentication(request, response, jwt);
}
protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response,
Jws<Claims> jwt) {
Claims claims = jwt.getBody();
validateTokenType(claims);
String clientType = claims.get(ApplicationConstants.JwtInfo.CLAIM_KEY_CLIENT_TYPE, String.class);
if (StringUtils.isNotBlank(clientType) && ApplicationConstants.ClientType.SUB_SYSTEM.equals(clientType)) {
return attemptSubSystemAuthentication(request, response, claims);
} else {
return attemptUserAuthentication(request, response, claims);
}
}
/**
* Make sure Jwt created is formatted according to the Google Cloud IoT Core<a
* href="https://cloud.google.com/iot/docs/how-tos/credentials/jwts#jwt_composition">spec</a>.
*/
@Test
public void testCreateJwtRsa() throws JoseException {
JwtGenerator jwtGenerator =
new JwtGenerator(RSA_KEY_PAIR, JWT_AUDIENCE, TOKEN_LIFETIME, TEST_CLOCK);
String rawJwt = jwtGenerator.createJwt();
// Validate JWT
Jws<Claims> parsedJwt = Jwts.parser()
.setSigningKey(RSA_KEY_PAIR.getPublic())
.parseClaimsJws(rawJwt);
JwsHeader header = parsedJwt.getHeader();
Claims claims = parsedJwt.getBody();
assertThat(header.getAlgorithm()).isEqualTo("RS256");
assertThat(header.getType()).isEqualTo("JWT");
assertThat(claims.getAudience()).isEqualTo(JWT_AUDIENCE);
// JWT requires time in seconds from epoch, not millis, so allow issue time within one
// second.
assertThat(claims.getIssuedAt().getTime()).isAtLeast(TEST_CLOCK.millis() - 1000);
assertThat(claims.getIssuedAt().getTime()).isAtMost(TEST_CLOCK.millis() + 1000);
// Check expiration time within one second of issue time + TOKEN_LIFETIME
assertThat(claims.getExpiration().getTime())
.isLessThan(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.plusSeconds(1)).millis());
assertThat(claims.getExpiration().getTime())
.isAtLeast(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.minusSeconds(1)).millis());
}
/**
* Make sure Jwt created is formatted according to the Google Cloud IoT Core<a
* href="https://cloud.google.com/iot/docs/how-tos/credentials/jwts#jwt_composition">spec</a>.
*/
@Test
public void testCreateJwtEc() throws JoseException {
JwtGenerator jwtGenerator =
new JwtGenerator(EC_KEY_PAIR, JWT_AUDIENCE, TOKEN_LIFETIME, TEST_CLOCK);
String rawJwt = jwtGenerator.createJwt();
// Validate JWT
Jws<Claims> parsedJwt;
try {
parsedJwt = Jwts.parser()
.setSigningKey(EC_KEY_PAIR.getPublic())
.parseClaimsJws(rawJwt);
} catch (UnsupportedJwtException | MalformedJwtException | SignatureException e) {
fail("Error parsing JWT: " + e);
return; // Satisfy compiler
}
JwsHeader header = parsedJwt.getHeader();
Claims claims = parsedJwt.getBody();
assertThat(header.getAlgorithm()).isEqualTo("ES256");
assertThat(header.getType()).isEqualTo("JWT");
assertThat(claims.getAudience()).isEqualTo(JWT_AUDIENCE);
// JWT requires time in seconds from epoch, not millis, so allow issue time within one
// second.
assertThat(claims.getIssuedAt().getTime()).isAtLeast(TEST_CLOCK.millis() - 1000);
assertThat(claims.getIssuedAt().getTime()).isAtMost(TEST_CLOCK.millis() + 1000);
// Check expiration time within one second of issue time + TOKEN_LIFETIME
assertThat(claims.getExpiration().getTime())
.isLessThan(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.plusSeconds(1)).millis());
assertThat(claims.getExpiration().getTime())
.isAtLeast(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.minusSeconds(1)).millis());
}
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) {
Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
Claims claims = jwsClaims.getBody();
String subject = claims.getSubject();
List<String> scopes = claims.get(SCOPES, List.class);
if (scopes == null || scopes.isEmpty()) {
throw new IllegalArgumentException("JWT Token doesn't have any scopes");
}
SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
securityUser.setEmail(subject);
securityUser.setAuthority(Authority.parse(scopes.get(0)));
securityUser.setFirstName(claims.get(FIRST_NAME, String.class));
securityUser.setLastName(claims.get(LAST_NAME, String.class));
securityUser.setEnabled(claims.get(ENABLED, Boolean.class));
boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
securityUser.setUserPrincipal(principal);
String tenantId = claims.get(TENANT_ID, String.class);
if (tenantId != null) {
securityUser.setTenantId(new TenantId(UUID.fromString(tenantId)));
}
String customerId = claims.get(CUSTOMER_ID, String.class);
if (customerId != null) {
securityUser.setCustomerId(new CustomerId(UUID.fromString(customerId)));
}
return securityUser;
}
private String getUserIfValid(String token) {
Key key = new SecretKeySpec("secret".getBytes(), "DES");
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(key)
.parseClaimsJws(token);
String scope = claims.getBody().get("scope", String.class);
System.out.println("scope " + scope);
return claims.getBody().getSubject();
} catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
//don't trust the JWT!
e.printStackTrace();
throw new NotAuthorizedException("Invalid JWT");
}
}
public boolean validateToken(String token) {
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
if (claims.getBody().getExpiration().before(new Date())) {
return false;
}
return true;
} catch (JwtException | IllegalArgumentException e) {
throw new InvalidJwtAuthenticationException("Expired or invalid JWT token");
}
}
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
// The library representations of the JWT should be kept internal to this service.
try {
final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);
if (jws == null) {
throw new JwtException("Unable to parse token");
}
// Additional validation that subject is present
if (StringUtils.isEmpty(jws.getBody().getSubject())) {
throw new JwtException("No subject available in token");
}
// TODO: Validate issuer against active registry?
if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
throw new JwtException("No issuer available in token");
}
return jws.getBody().getSubject();
} catch (JwtException e) {
logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
final String errorMessage = "There was an error validating the JWT";
// A common attack is someone trying to use a token after the user is logged out
// No need to show a stacktrace for an expected and handled scenario
String causeMessage = e.getLocalizedMessage();
if (e.getCause() != null) {
causeMessage += "\n\tCaused by: " + e.getCause().getLocalizedMessage();
}
if (logger.isDebugEnabled()) {
logger.error(errorMessage, e);
} else {
logger.error(errorMessage);
logger.error(causeMessage);
}
throw e;
}
}
@Override
public Authentication authenticate(final HttpServletRequest request) {
final String token = request.getHeader(SecurityConstants.AUTH_HEADER_NAME);
final Jws<Claims> tokenData = parseToken(token);
if (tokenData != null) {
User user = getUserFromToken(tokenData);
if (user != null) {
return new UserAuthentication(user);
}
}
return null;
}
private Jws<Claims> parseToken(final String token) {
if (token != null) {
try {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
| SignatureException | IllegalArgumentException e) {
return null;
}
}
return null;
}
@Override
public Subject extractSubject(String token) throws ServletException {
Jws<Claims> jwt = jwtParser.parseClaimsJws(token);
Claims claims = jwt.getBody();
LOG.debug("JWT = {}", jwt);
// OK, we can trust this JWT
try {
String username =
claims.get(
keycloakSettings.get().get(KeycloakConstants.USERNAME_CLAIM_SETTING), String.class);
if (username == null) { // fallback to unique id promised by spec
// https://openid.net/specs/openid-connect-basic-1_0.html#ClaimStability
username = claims.getIssuer() + ":" + claims.getSubject();
}
String id = claims.getSubject();
String email =
retrieveEmail(token, claims, id)
.orElseThrow(
() ->
new JwtException(
"Unable to authenticate user because email address is not set in keycloak profile"));
User user = userManager.getOrCreateUser(id, email, username);
return new AuthorizedSubject(
new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker);
} catch (ServerException | ConflictException e) {
throw new ServletException(
"Unable to identify user " + claims.getSubject() + " in Che database", e);
}
}
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) {
try {
return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() {
@Override
public Jws<String> onPlaintextJws(Jws<String> jws) {
return jws;
}
});
} catch (IllegalArgumentException iae) {
throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
}
}
@Override
public Jws<Claims> parseClaimsJws(String claimsJws) {
return parse(claimsJws, new JwtHandlerAdapter<Jws<Claims>>() {
@Override
public Jws<Claims> onClaimsJws(Jws<Claims> jws) {
return jws;
}
});
}
/**
* Creates and validates Refresh token
*
* @param token
* @param signingKey
*
* @throws BadCredentialsException
* @throws JwtExpiredTokenException
*
* @return
*/
public static Optional<RefreshToken> create(RawAccessJwtToken token, String signingKey) {
Jws<Claims> claims = token.parseClaims(signingKey);
List<String> scopes = claims.getBody().get("scopes", List.class);
if (scopes == null || scopes.isEmpty()
|| !scopes.stream().filter(scope -> Scopes.REFRESH_TOKEN.authority().equals(scope)).findFirst().isPresent()) {
return Optional.empty();
}
return Optional.of(new RefreshToken(claims));
}
/**
* Parses and validates JWT Token signature.
*
* @throws BadCredentialsException
* @throws JwtExpiredTokenException
*
*/
public Jws<Claims> parseClaims(String signingKey) {
try {
return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
} catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
logger.error("Invalid JWT Token", ex);
throw new BadCredentialsException("Invalid JWT token: ", ex);
} catch (ExpiredJwtException expiredEx) {
logger.info("JWT Token is expired", expiredEx);
throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
}
}