JSON Web Token – 在 Web 应用间安全地传递信息
八幅漫画理解使用 JSON Web Token 设计单点登录系统
使用开源的https://jwt.io来实现
首先在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);
标签:几篇,level,JWT,jwt,String,key,讲解,claims,name From: https://blog.51cto.com/u_14230175/5923418