Java生成Token
1.Token依赖包
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2.Token生成的类
public class JwtUtils {
// 7天过期
private static long expire=60*60*24*7;
// 32位密钥
private static String secret="abcdefghabcdefghabcdefgh";
// 生成token
public static String generateToken(String username){
//当前时间
Date date=new Date();
//失效时间(时间是毫秒值)
Date expiration=new Date(date.getTime()+1000*expire);
return Jwts.builder()
.setHeaderParam("type","JWT")
.setSubject(username)
.setIssuedAt(date)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512,secret)
.compact();
}
// 解析Token的方法
public static Claims getClaimsByToken(String token){
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
}
3.扩展:返回给前端的结果集
![](https://i-blog.csdnimg.cn/blog_migrate/199b441f90f26fcf41b45fc0f4856877.png)