依赖导入
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
概念
- JWT 本质就是一个字符串,它将用户信息保存到一个 Json 字符串中,然后编码得到的字符串(Token)
- 该字符串带有签名信息效果,前端每次请求都携带 token ,后端接收后可以校验是否被篡改
使用
创建Token
private static final long EXPIPE_TIME = 3600 * 60 * 1000;
private static final String SECRET = "MiYao";
public static String sign(String userId) {
try {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT.create()
.withAudience(userId)
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
return null;
}
}
public static String getUserId(String token) {
try {
String userId = JWT.decode(token).getAudience().get(0);
return userId;
} catch (JWTDecodeException e) {
return null;
}
}
校检 Token
private static final String SECRET = "MiYao";
public static boolean checkSign(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (JWTVerificationException exception) {
return false;
}
}