当前位置:网站首页>【项目实训】jwt
【项目实训】jwt
2022-06-12 01:13:00 【par_ser】
JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
上述是jwt的官网的介绍,简单来说,使用jwt,可以安全地传输信息,jwt可以被验证。在我们的系统里,jwt主要用于授权。
jwt结构
JWT由三部分组成,分别是Header、Payload、Signature,中间使用点进行分隔。
JWT第一部分是头部分,它是一个描述JWT元数据的Json对象,通常如下所示。
{
"alg": "HS256",
"typ": "JWT"
}
alg属性表示签名使用的算法,默认为HMAC SHA256(写为HS256),typ属性表示令牌的类型,JWT令牌统一写为JWT。
最后,使用Base64 URL算法将上述JSON对象转换为字符串保存。
JWT第二部分是Payload,也是一个Json对象,除了包含需要传递的数据,还有七个默认的字段供选择。
分别是,iss:发行人、exp:到期时间、sub:主题、aud:用户、nbf:在此之前不可用、iat:发布时间、jti:JWT ID用于标识该JWT。
JWT第三部分是签名。是这样生成的,首先需要指定一个secret,该secret仅仅保存在服务器中,保证不能让其他用户知道。然后使用Header指定的算法对Header和Payload进行计算,然后就得出一个签名哈希。也就是Signature。
jwt优势
谈起jwt,我们经常会跟传统的session方案做比较,jwt的一个显而易见的优势是无状态,通俗地来讲,就是服务器不需要针对每一个”登录“用户来存储额外的信息做用户授权。发出去的jwt你不需要知道是什么,而只需要按照既定的解析方法去解析即可。(但无状态并不如想象的那般美好,它也会带来不少问题,例如在不引入额外措施的情况下,让一个jwt失效恐怕很困难,这意味着,哪怕用户登出了,如果jwt没到过期时间,你接着用它依然能正常访问接口)
此外,jwt的优势还有:从根本上防止了CSRF攻击(jwt对前端不像cookie那样透明,你可以将jwt放在header中携带发送出去),适合移动端应用(不依赖cookie..),容易实现单点登录等。
添加依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>创建工具类
进一步地,为了让我们更便捷地创建jwt,可以定义一个工具类(可类似如下来定义方法)
public static String createJWT(String subject, Long ttlMillis,String decodeKey) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID(),decodeKey);// 设置过期时间
return builder.compact();
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid, String decodeKey) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey(decodeKey);
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid) //唯一的ID
.setSubject(subject) // 主题 可以是JSON数据
.setIssuer("wodeqianming") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
.setExpiration(expDate); //过期时间
}边栏推荐
- The CSV used for JMeter performance test is bullshit
- Ms-hgat: information diffusion prediction based on memory enhanced sequence hypergraph attention network
- Lambda中间操作flatMap
- 语义向量检索入门教程
- Advanced data storage
- Sharing of Manta network parallel chain solutions by Hufu Research Institute
- How can functional tests be quickly advanced in one month? It is not a problem to clarify these two steps
- jvm: 线程上下文类加载器(TheadContextClassLoader)
- How to optimize plantuml flow diagram (sequence diagram)
- Component introduction - large screen cloud minimalist user manual
猜你喜欢

Kill, pkill, killall, next, what I brought to you in the last issue is how to end the process number and rush!
![Article 7: Design of multifunctional intelligent trunk following control system | undergraduate graduation project - [module device selection, list and data]](/img/9f/4337d5064d9fc93da4c17784a3accc.jpg)
Article 7: Design of multifunctional intelligent trunk following control system | undergraduate graduation project - [module device selection, list and data]

Building circuits on glass

Nat. Comm. | 超算+AI: 为天然产物生物合成路线规划提供导航

Zhongchuang patents | China has 18000 necessary patents for 5g standards, respects intellectual property rights and jointly builds a strong intellectual property country

Redis advanced - correspondence between object and code base

Kill session? This cross domain authentication solution is really elegant

Module 8 - Design message queue MySQL table for storing message data

Jvm: thread context classloader

MS-HGAT: 基于记忆增强序列超图注意力网络的信息扩散预测
随机推荐
Lambda终结操作forEach
Equipment encryption of industrial control security
Yixin Huachen talks about how to do a good job in customer master data management
Websocket server practice
2022 edition of global and Chinese sodium hydrosulfide market in-depth investigation and prospect Trend Forecast Report
VsCode - 保存文件自动格式化将单引号 ‘ 变成双引号 “ 的问题
Devops landing practice drip and pit stepping records - (1)
Nat. Comm. | 超算+AI: 为天然产物生物合成路线规划提供导航
Sharing of Manta network parallel chain solutions by Hufu Research Institute
Lambda intermediate operation skip
Weekly CTF 第一周:神奇的磁带
Chapter V - Fund professional ethics
websocket服务器实战
一看就懂的JMeter操作流程
Recurrent+Transformer 视频恢复领域的‘德艺双馨’
I'm fired because I can only test basic functions····
Industry competition analysis and investment scale research report of global and Chinese micro potato industry 2022-2028
王希廷博士:从知识图谱和自然语言生成的角度认识可解释推荐
Analysis report on operation trends and development strategies of global and Chinese plastic adhesive industry 2022-2028
Comparison of OpenCV basic codes of ros2 foxy~galactic~humble