public Authentication getAuthentication(String token) { Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); }
public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature: " + e.getMessage()); return false; } }
public String createToken(Authentication authentication, Boolean rememberMe) { String authorities = authentication .getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(SignatureAlgorithm.HS512, secretKey) .setExpiration(validity) .compact(); }