Spring boot 使用JWT
引入pom.xml依赖
io.jsonwebtoken
jjwt
0.9.1
jdk1.8以上还需要引入3个辅助包
编写代码:
@SpringBootTest
class JwtApplicationTests {
private long time=1000*60*24;//1天的时间
private String singature="admin";//签名的key
@Test
void contextLoads() {
JwtBuilder builder = Jwts.builder();
String jwtToken=builder
//header
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
//payload
.claim("username","tom") //用户名
.claim("role","admin")//用户身份
.setSubject("admin-test")//主题,随便写的
.setExpiration(new Date(System.currentTimeMillis()+time))//过期时间,设置1天
.setId(UUID.randomUUID().toString())//id
.signWith(SignatureAlgorithm.HS256,singature).compact();//使用HS256加密并拼接
System.out.println(jwtToken);
}
@Test
void parseToken(){//解密token
String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2Mzc4MjI5MTMsImp0aSI6IjM3YjgyZGU4LWU5M2EtNGE4MC05NTRiLWRjZTI0YzQ0ZDM3ZCJ9.S6FZ77bLtpZJXF15QT3xWr8X06PJbW5QQz8wshkLULI";
JwtParser jwtParser=Jwts.parser();
jwtParser.setSigningKey(singature);
JwsclaimsJwt = jwtParser.parseClaimsJws(token);
Claims body = claimsJwt.getBody();
body.get("username");//获取用户名
body.getExpiration();//过期时间
Iterator> iterator = body.entrySet().iterator();
while (iterator.hasNext()){
System.out.println(iterator.next().getValue());
}
}
}