JWT
- 依赖
```java io.jsonwebtoken jjwt 0.9.1
commons-codec commons-codec ```
- 工具类
```java public class JwtUtils {
private static final String SECRET = "123456@$$"; // 给token加密的秘钥
// 创建token
public static String createToken(Long userId) {
HashMap<String, Object> claims = new HashMap<>();
claims.put("userId", userId);
JwtBuilder jwtBuilder = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, SECRET)
.setClaims(claims)
.setIssuedAt(new Date())
.setExpiration(new Date(new DateTime().getMillis() + 24 * 60 * 60 * 1000));
String token = jwtBuilder.compact();
return token;
}
// 验证token
public static Map<String,Object> checkToken(String token) {
try {
Jwt parse = Jwts.parser().setSigningKey(SECRET).parse(token);
return (Map<String,Object>)parse.getBody();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 测试
public static void main(String[] args) {
String token = JwtUtils.createToken(413977414L);
System.out.println(token);
Map<String, Object> map = JwtUtils.checkToken(token);
System.out.println(map);
}
} ```