JWT(json web token)
程序员文章站
2024-02-04 08:31:22
...
token由head头部,payLoad消息体,signature签名
maven导入
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
创建token
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class CreateJWT {
public static void main(String[] args) {
String priKey="dajitui123";
JwtBuilder builder= Jwts.builder().setId("123").setSubject("jwt测试").setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256,priKey);
String s=builder.compact();
System.out.println(s);
//eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjMiLCJzdWIiOiJqd3TmtYvor5UiLCJpYXQiOjE1NDQ4Njc2MzB9.KYZvcS3dhIjOfkfRjzv5kbVgDbriCIDoll6y2ZVBvRQ
}
}
解密信息
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
public class ParseJWT {
public static void main(String[] args) {
String pubKey="dajitui123";
String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjMiLCJzdWIiOiJqd3TmtYvor5UiLCJpYXQiOjE1NDQ4NjkxMTF9.uIQ4o7N9x5JGmUVg8RcJlwqS3IXBjfRh-V_n61FBwW0";
try {
Claims claims= Jwts.parser().setSigningKey(pubKey).parseClaimsJws(token).getBody();
System.out.println("id"+claims.getId());
System.out.println("subject"+claims.getSubject());
System.out.println("issuedAt"+claims.getIssuedAt());
}catch (SignatureException e){
System.out.println("**错误");
}
}
}
上一篇: 编码习惯-函数编写建议