当前位置: 首页 > news >正文

jjwt使用说明-笔记

jjwt官网链接:https://github.com/jwtk/jjwt

POM 依赖

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId><version>0.12.3</version>
</dependency>
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><version>0.12.3</version><scope>runtime</scope>
</dependency>
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --><version>0.12.3</version><scope>runtime</scope>
</dependency>
<!-- Uncomment this next dependency if you are using:
- JDK 10 or earlier, and you want to use RSASSA-PSS (PS256, PS384, PS512) signature algorithms.  
- JDK 10 or earlier, and you want to use EdECDH (X25519 or X448) Elliptic Curve Diffie-Hellman encryption.
- JDK 14 or earlier, and you want to use EdDSA (Ed25519 or Ed448) Elliptic Curve signature algorithms.    
It is unnecessary for these algorithms on JDK 15 or later.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId> or bcprov-jdk15to18 on JDK 7
<version>1.76</version>
<scope>runtime</scope>
</dependency>
-->

生成token

PS: 基本和java-jwt使用一致。只是最新的jjwt舍弃了一些api,换了新的api

① 标准载荷:
JwtBuilder为JWT规范中定义的标准载荷提供了方便的构建器方法。
● issuer: sets the iss(Issuer) Claim jwt签发者
● subject: sets the sub(Subject) Claim jwt针对的用户
● audience: sets the aud(Audience) Claim 校验jwt的一方
● expiration: sets the exp(Expiration Time) Claim jwt过期时间
● notBefore: sets the nbf(Not Before) Claim 定义在某个时间前该jwt是不可用的
● issuedAt: sets the iat(Issued At) Claim 签发时间
● id: sets the jti(JWT ID) Claim jwt的唯一身份标识,作一次性token,防重放攻击。
② 自定义载荷:
● claime(key,value)
● claime(Map对象)

// 创建token密钥的key,并且使用 HMAC-SHA-256 加密算法
private static SecretKey key = Jwts.SIG.HS256.key().build();/*** 生成token* @return*/
public static String genToken(){// 2. 构建jwt,将签发人设置为joe,并且使用密钥将签名jwt生成为jwsString jws =  Jwts.builder().subject("Joe").  // setSubject 设置jwt针对的用户issuer("张三").   // issuer 签发人claim("name","zhangsan"). // 自定义载荷数据claim("role","admin"). // 自定义载荷数据signWith(key).   // token加签认证expiration(new Date(System.currentTimeMillis()+7200*1000)). // 设置token过期时间为2Hcompact();  // 生成token字符串return jws;
}

生成token的两句核心代码:

SecretKey key = Jwts.SIG.HS256.key().build();
Jwts.builder().setSubject("Joe").signWith(key).compact();

验证解析token

 /*** token 校验* @param key  密钥* @param token jws* @return*/
public static String checkToken(SecretKey key,String token ){String msg = null;try {Jws<Claims> claimsJws = Jwts.parser().verifyWith(key).build().parseSignedClaims(token);// 获取载荷的一些数据信息Claims payload = claimsJws.getPayload(); // payload 为一个map对象String issuer = payload.getIssuer();Date expiration = payload.getExpiration();String name = (String)payload.get("name");String role = (String)payload.get("role");// 测试就直接打印出去了...System.out.println("标准载荷:issuer===>"+issuer+"\texpiration=>"+expiration + "自定义载荷数据:"+name+"\t"+role);return "token正确";} catch (SignatureException se) {msg = "密钥错误";return  msg;}catch (MalformedJwtException me) {msg = "密钥算法或者密钥转换错误";return  msg;}catch (MissingClaimException mce) {msg = "密钥缺少校验数据";return  msg;}catch (ExpiredJwtException mce) {msg = "密钥已过期";return  msg;}catch (JwtException jwte) {msg = "密钥解析错误";return  msg;}
}

完整代码

package jwt_test;import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
import javax.crypto.SecretKey;
import java.util.Date;/*** jjwt*/
public class JJwtUtils {// 创建token密钥的key,并且使用 HMAC-SHA-256 加密算法private static SecretKey key = Jwts.SIG.HS256.key().build();/*** 生成token* @return*/public static String genToken(){// 2. 构建jwt,将签发人设置为joe,并且使用密钥将签名jwt生成为jwsString jws =  Jwts.builder().subject("Joe").  // setSubject 设置jwt针对的用户issuer("张三").   // issuer 签发人claim("name","zhangsan"). // 自定义载荷数据claim("role","admin"). // 自定义载荷数据signWith(key).   // token加签认证expiration(new Date(System.currentTimeMillis()+7200*1000)). // 设置token过期时间为2Hcompact();  // 生成token字符串return jws;}/*** token 校验* @param key  密钥* @param token jws* @return*/public static String checkToken(SecretKey key,String token ){String msg = null;try {Jws<Claims> claimsJws = Jwts.parser().verifyWith(key).build().parseSignedClaims(token);// 获取载荷的一些数据信息Claims payload = claimsJws.getPayload(); // payload 为一个map对象String issuer = payload.getIssuer();Date expiration = payload.getExpiration();String name = (String)payload.get("name");String role = (String)payload.get("role");// 测试就直接打印出去了...System.out.println("标准载荷:issuer===>"+issuer+"\texpiration=>"+expiration + "自定义载荷数据:"+name+"\t"+role);return "token正确";} catch (SignatureException se) {msg = "密钥错误";return  msg;}catch (MalformedJwtException me) {msg = "密钥算法或者密钥转换错误";return  msg;}catch (MissingClaimException mce) {msg = "密钥缺少校验数据";return  msg;}catch (ExpiredJwtException mce) {msg = "密钥已过期";return  msg;}catch (JwtException jwte) {msg = "密钥解析错误";return  msg;}}/*** 	测试*/public static void main(String[] args) {String token = genToken();System.out.println(token);// 断言测试// assert Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload().getSubject().equals("Joe");String res = checkToken(key, token);System.out.println(res);}}

在这里插入图片描述

相关文章:

  • win10 怎么进入cmd窗口
  • VBA技术资料MF85:将工作簿批量另存为PDF文件
  • django ModelSerializer自定义显示字段
  • msvcp140.dll是什么?msvcp140.dll丢失的有哪些解决方法
  • 90.子集II
  • Linux中的进程程序替换
  • 点云从入门到精通技术详解100篇-基于点云数据的机器人装焊 过程在线测量(下)
  • 如何解决msvcp110.dll丢失问题,分享5个有效的解决方法
  • 自动驾驶轨迹预测学习笔记
  • uniapp 富文本以及移动端富文本的展示问题
  • 力扣算法练习BM46—最小的K个数
  • Echarts+vue+java+mysql实现数据可视化
  • Linux文件I/O:基本概念
  • K8s client go 创建CRD的informer
  • 3.volatile基本原理及缺陷
  • 【跃迁之路】【519天】程序员高效学习方法论探索系列(实验阶段276-2018.07.09)...
  • create-react-app项目添加less配置
  • HTML中设置input等文本框为不可操作
  • iOS 系统授权开发
  • Iterator 和 for...of 循环
  • Javascript Math对象和Date对象常用方法详解
  • JavaScript 基本功--面试宝典
  • mysql常用命令汇总
  • MySQL几个简单SQL的优化
  • SpingCloudBus整合RabbitMQ
  • UEditor初始化失败(实例已存在,但视图未渲染出来,单页化)
  • Vim 折腾记
  • Vue 2.3、2.4 知识点小结
  • 爱情 北京女病人
  • -- 查询加强-- 使用如何where子句进行筛选,% _ like的使用
  • 后端_ThinkPHP5
  • 前端每日实战:61# 视频演示如何用纯 CSS 创作一只咖啡壶
  • 视频flv转mp4最快的几种方法(就是不用格式工厂)
  • #数学建模# 线性规划问题的Matlab求解
  • $GOPATH/go.mod exists but should not goland
  • (2)MFC+openGL单文档框架glFrame
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (转)fock函数详解
  • (转)拼包函数及网络封包的异常处理(含代码)
  • .jks文件(JAVA KeyStore)
  • .NET Core、DNX、DNU、DNVM、MVC6学习资料
  • .Net Memory Profiler的使用举例
  • .NET WebClient 类下载部分文件会错误?可能是解压缩的锅
  • .NET/ASP.NETMVC 深入剖析 Model元数据、HtmlHelper、自定义模板、模板的装饰者模式(二)...
  • .net安装_还在用第三方安装.NET?Win10自带.NET3.5安装
  • .NET的微型Web框架 Nancy
  • /usr/bin/python: can't decompress data; zlib not available 的异常处理
  • @Autowired和@Resource装配
  • [ C++ ] STL---stack与queue
  • [2]十道算法题【Java实现】
  • [2017][note]基于空间交叉相位调制的两个连续波在few layer铋Bi中的全光switch——
  • [AIGC] 开源流程引擎哪个好,如何选型?
  • [Android] Upload package to device fails #2720
  • [android学习笔记]学习jni编程
  • [AutoSar]BSW_Com07 CAN报文接收流程的函数调用