- 导入jar包
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
- 编写工具类
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtil {
private final static String key = "!@#$%^&*IUYTJ$^DSADSsa2132ADSASDA#^%$^$%^$&DYsaFGGS#@$%$#^";
public static String createToken() {
return Jwts.builder()
.setIssuedAt(new Date())//设置创建时间
.claim("username", "张三")//设置私有字段
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60*15))//设置过期时间15分钟
.signWith(SignatureAlgorithm.HS512, key)//加密
.compact();//打包
}
public static boolean verify(String token) {
return getTokenClaims(token) != null;
}
public static Claims getTokenClaims(String token) {
try {
return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
String token = createToken();
System.out.println(token);
System.out.println(verify(token));
System.out.println(getTokenClaims(token).get("username"));
}
}