相关介绍
1)JWT
JWT:全称 JSON Web Token,是一个分布式身份校验方案,可生产 token,也可解析 token
JWT生成的 token 由三部分组成:
- 头部:主要设置一些规范信息,签名部分的编码格式就在头部声明
- 载荷:token 中存放有效信息的部分。比如用户名、角色、过期时间等,切记不要放密码,会泄露
- 签名:将头部与载荷分别采用base64编码后,用“.”相连,再加入盐,最后使用头部声明的编码类型进行编码,就得到了签名。
2)RSA 非对称加密
基本原理:同时生成两把密钥(公钥和私钥),私钥隐秘保存,公钥可发放给信任的客户端
- 私钥加密:持有私钥或公钥可解密
- 公钥加密:持有私钥才可解密
优点:安全,难以破解
缺点:算法耗时,但可以接受
3)项目说明
以下只贴关键代码,需要完整代码见本文末尾 github 链接
公共模块
1)首先创建一个父工程,把其中 src 目录删除,添加 pom 依赖,主要添加 springboot 依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
2)在该工程下创建子模块----公共模块
该模块放了一些 JWT 和 RSA 的工具类,因此需要加入 jwt 和 json 相关的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springsecurity_jwt_parent</artifactId>
<groupId>com.xiao</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common_module</artifactId>
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.1</version>
<scope>runtime</scope>
</dependency>
&l