使用jdk17
环境,并在pom.xml
中导入jjwt
依赖:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
工具类JwtUtils
代码
public class JwtUtils {
private static String signKey = "buaa";
private static Long expire = 100000000L;
public static String genToken(Map<String, Object> claims) {
String token = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS256, signKey)
.setExpiration(new Date(System.currentTimeMillis() + expire))
.compact();
return token;
}
public static Claims parseToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(signKey)
.parseClaimsJws(token)
.getBody();
return claims;
}
}
测试类代码
public class JwtTest {
@Test
public void testGen() {
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1);
claims.put("username", "Ivo10");
String token = JwtUtils.genToken(claims);
System.out.println(token);
}
@Test
public void testParse() {
Claims claims = JwtUtils.parseToken("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNzAwMTUxMDQ0LCJ1c2VybmFtZSI6Ikl2bzEwIn0.EacSVOXZZs3raNh7iESAJoZj2dZ_E9o9oRz5rj4Naug");
System.out.println(claims);
}
}
发现报如下错误:
pom.xml
中引入相关依赖:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
解决,成功生成JWT令牌:
附:JWT令牌介绍
- 官网
- 组成部分
- Header:记录令牌类型、签名算法等;
- Payload:携带一些自定义信息、默认信息等;
- Signature:防止 Token被篡改,确保安全性。将header、payload,并加入指定密钥,通过指定签名算法计算而来;