GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

JWT token的生成和解析

使用java-jwt

创建和解析JWT,可以使用如下依赖:

1
2
3
4
5
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>

创建token

1
2
3
4
5
6
7
8
/** 生成JWT **/
public String createToken(String name, String userId, String email) throws IllegalArgumentException, UnsupportedEncodingException{
JWTCreator.Builder builder = JWT.create();
Algorithm algorithm = Algorithm.HMAC256("xxxxx"); //另外一端解析时也需要这个密码
String token = builder.withClaim("name", name.withClaim("user_id", userId).withClaim("email", email)
.withExpiresAt(new Date(new Date().getTime() + 24*3600*1000)).sign(algorithm);
return token;
}

解析token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/** 解析JWT **/
public User parseJwt(String token){
User = new User();
try {
Algorithm algorithm = Algorithm.HMAC256("xxxxx"); // 另外一端解析时也需要这个密码
JWTVerifier verifier = JWT.require(algorithm).acceptExpiresAt(5).build(); // Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
String userId = jwt.getClaim("user_id").asString();
String name = jwt.getClaim("name").asString();
String email = jwt.getClaim("email").asString();
user.setId(userId);
user.setName(name);
user.setEmail(email);
} catch (JWTVerificationException | IllegalArgumentException | UnsupportedEncodingException e) {
log.error("无效的token" + token, e);
return null;
} catch (Throwable e) {
log.error("验证token异常:" + token, e);
return null;
}
return user;
}

上面是用了相同的密码做的签名,也可以用RSA的公钥私钥。