maven进入包
<!-- start jwt引入-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- end jwt引入-->
Jwt工具类
package com.bruce.common.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class JwtUtil {
private static final String secret ="asdfasdf";
public static String createToken(String subject) {
String token = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() +1000 *30)).setSubject(subject).signWith(SignatureAlgorithm.HS256,secret).compact();
return token;
}
public static String parseToken(String token) {
Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
String subject = body.getSubject();
return subject;
}
public static void main(String[] args) {
try {
String name ="关云长";
String token =createToken(name);
System.out.println("token:" + token);
TimeUnit.SECONDS.sleep(4);
String srcStr =parseToken(token);
System.out.println("解析出来:" + srcStr);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
网友评论