String token = jwtBuilder.compact();
return token;
}
/**
-
生成Token令牌
-
@param userDetails 用户
-
@return 令牌Token
*/
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(“sub”, userDetails.getUsername());
claims.put(“created”, new Date());
return generateToken(claims);
}
/**
-
从token中获取数据声明claim
-
@param token 令牌token
-
@return 数据声明claim
*/
public Claims getClaimsFromToken(String token) {
try {
SecretKey key = getSecretKey(secret);
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token)
.getBody();
return claims;
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
log.error(“token解析错误”, e);
throw new IllegalArgumentException(“Token invalided.”);
}
}
public String getUserRole(String token) {
return (String) getClaimsFromToken(token).get(“role”);
}
/**
-
从token中获取登录用户名
-
@param token 令牌
-
@return 用户名
*/
public String getSubjectFromToken(String token) {
String subject;
try {
Claims claims = getClaimsFromToken(token);
subject = claims.getSubject();
} catch (Exception e) {
subject = null;
}
return subject;
}
/**
-
获取token的过期时间
-
@param token token
-
@return 过期时间
*/
public Date getExpirationFromToken(String token) {
return getClaimsFromToken(token).getExpiration();
}
/**
-
判断token是否过期
-
@param token 令牌
-
@return 是否过期:已过期返回true,未过期返回false
*/
public Boolean isTokenExpired(String token) {
Date expiration = getExpirationFromToken(token);
return expiration.before(new Date());
}
/**
-
验证令牌:判断token是否非法
-
@param token 令牌
-
@param userDetails 用户
-
@return 如果token未过期且合法,返回true,否则返回false
*/
public Boolean validateToken(String token, UserDetails userDetails) {
//如果已经过期返回false
if (isTokenExpired(token)) {
return false;
}
String usernameFromToken = getSubjectFromToken(token);
String username = userDetails.getUsername();
return username.equals(usernameFromToken);
}
}
- 测试代码
@SpringBootTest
public class JwtUtilTest {
@Resource
private JwtUtil jwtUtil;
@Resource
private PasswordEncoder passwordEncoder;
@Test
void fun() {
System.out.println(passwordEncoder);
SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
System.out.println(secretKey);
}
//生成token
@Test
void generateToken() {
//用户信息
String encode = passwordEncoder.encode(“1234”);
User user = new User(“zhangsan”, encode, AuthorityUtils.createAuthorityList());
String token = jwtUtil.generateToken(user);
System.out.println