在开发过程中我们通常会用开源库来实现JWT相关功能(不知道JWT的点这里),本篇文章会用JJWT来作示范
首先在pom.xml中引入依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
创建
创建JWT之前首先要创建一个base64需要的key
import io.jsonwebtoken.*;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
...
String stringKey ="lwlsecret";
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
然后根据这个secret创建jwt
//设置算法为HS256
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date now = new Date(System.currentTimeMillis());
JwtBuilder builder = Jwts.builder()
.setHeaderParam("typ", "JWT") //设置header
.setHeaderParam("alg", "HS256")
.setIssuedAt(now) //设置iat
.claim("name", "liuwillow") //设置payload的键值对
.claim("level", "100")
.setIssuer("lwl")
.signWith(signatureAlgorithm, key); //签名,需要算法和key
String jwt = builder.compact();
System.out.println("生成的jwt:" + jwt);
即可输出得到的jwt字符串
验证
//获取claims
Claims claims = Jwts.parser()
.setSigningKey(key) //此处的key要与之前创建的key一致
.parseClaimsJws(jwt)
.getBody();
//获取name和level
String name = (String) claims.get("name");
String level = (String) claims.get("level");
System.out.println("name:" + name + " level:" + level);