JWT 是 Json Web Token的缩写
JWT 的结构格式如下:
xxxxx.yyyyy.zzzzz
由三部分组成,每部分 用 点 分割
第一部分:
头部,记录 使用的 加密算法的类型
第二部分:
Body,记录一些额外信息
第三部分:
签名,用来校验 数据是否 被篡改
OK,Java工具包如下,使用 jjwt
- <dependency>
- <groupId>io.jsonwebtokengroupId>
- <artifactId>jjwtartifactId>
- <version>0.9.0version>
- dependency>
OK,生成一个 JWT 步骤:
确定 使用的加密算法,jjwt 工具包已经 给我们提供好了各种加密算法的枚举
io.jsonwebtoken.SignatureAlgorithm
确定 使用的秘钥
SecretKey secretKey = new SecretKeySpec("秘钥字符串".getBytes(), "AES");
构建Body部分,该部分 是一个 Map
另外,可以构建 JWT 的创建时间 和 失效时间
- String jwtToken = Jwts.builder()
- .setClaims()
- .setIssuedAt()
- .signWith()
- .setExpiration()
- .compact();
OK,解析 JWT
使用和 生成 JWT 相同的 秘钥,因为 token中已经有 算法信息了,所以不用再设置算法。
- Claims claims = Jwts.parser()
- .setSigningKey()
- .parseClaimsJws()
- .getBody();
解析获取到 Claims 对象,可以获取 body 中的数据。
完整示例代码:
- // 生成token
- // 签名算法
- SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
- // 加密秘钥
- SecretKey secretKey = new SecretKeySpec("1234567890".getBytes(), "AES");
-
- // body部分
- Map
body = new HashMap<>(); - body.put("userId", "0001");
-
- // 创建时间 和 实效时间
- long nowMillis = System.currentTimeMillis();
- long expMillis = nowMillis + 1000 * 60 * 1;
- Date iat = new Date(nowMillis);
- Date exp = new Date(expMillis);
- //生成jwt
- String jwtToken = Jwts.builder()
- .setClaims(body)
- .setIssuedAt(iat)
- .signWith(algorithm, secretKey)
- .setExpiration(exp)
- .compact();
- System.out.println(jwtToken);
-
- // Thread.sleep(1000 * 61 * 1);
-
- // 验证
- // 获取解密秘钥
- SecretKey key = new SecretKeySpec("1234567890".getBytes(), "AES");
-
- // 解析token
- Claims claims = Jwts.parser()
- .setSigningKey(key)
- .parseClaimsJws(jwtToken).getBody();
-
- Object userId = claims.get("userId");
- System.out.println("userId:" + userId);
如果 token 失效 或者 加密 秘钥和解密秘钥 不同,都会解析失败。
在需要权限校验的资源中,就可以 从请求信息中获取 jwt 来验证 权限。