首先需要引入相关的依赖包
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
直接写个简单的DEMO吧,如下:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
public class Demo {
//颁发令牌使用的密钥
private static String SIGNING_KEY = "12132433454";
/**
* 颁发令牌
* @return
*/
public static String createToken(){
SecretKey key = new SecretKeySpec(SIGNING_KEY.getBytes(),"AES");
JwtBuilder builder= Jwts.builder()
.setIssuedAt(new Date())//设置签发时间
.setId("1")//
.setSubject("测试")
//.setExpiration(null) //过期时间
.signWith(SignatureAlgorithm.HS256,key);
return builder.compact();
}
/**
* 通过token获取信息
* @param token
*/
public static void checkToken(String token){
try{
SecretKey key = new SecretKeySpec(SIGNING_KEY.getBytes(),"AES");
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
System.out.println("id: " + claims.getId());
System.out.println("subject: " + claims.getSubject());
}catch (Exception e){
System.out.println("解密异常 : " + e.getMessage());
}
}
/**
* 测试
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
String token = createToken();//颁发令牌
System.out.println("令牌: " + token);
checkToken(token);//解密令牌
}
}