JavaWeb合集16-JWT令牌验证

ops/2024/10/29 22:31:35/

十六、JWT令牌验证

JWT(JSON Web Token)是一种用于在网络上安全传输信息的紧凑、URL 安全的表示形式。它是一种无状态的身份验证机制,常用于现代Web应用和服务之间传递用户身份信息或授权数据。JWT 设计用于在各方之间安全地传输信息,并且信息是可以被验证和信任的。

JWT 由三个部分组成,它们通过点(.)分隔,头部(Header)、负载(Payload)、签名(Signature)。

使用场景:用户身份验证、单点登录、微服务间的通信、移动应用认证等

用户身份验证流程:用户登录、服务器验证、客户端存储JWT、请求附带JWT、服务器验证JWT。

1、具体实现

1、导入对应的jar包

        token comment"><!--JWT令牌-->token tag">token tag">token punctuation"><dependencytoken punctuation">>token tag">token tag">token punctuation"><groupIdtoken punctuation">>io.jsonwebtokentoken tag">token tag">token punctuation"></groupIdtoken punctuation">>token tag">token tag">token punctuation"><artifactIdtoken punctuation">>jjwt-apitoken tag">token tag">token punctuation"></artifactIdtoken punctuation">>token tag">token tag">token punctuation"><versiontoken punctuation">>0.12.5token tag">token tag">token punctuation"></versiontoken punctuation">>token tag">token tag">token punctuation"></dependencytoken punctuation">>token tag">token tag">token punctuation"><dependencytoken punctuation">>token tag">token tag">token punctuation"><groupIdtoken punctuation">>io.jsonwebtokentoken tag">token tag">token punctuation"></groupIdtoken punctuation">>token tag">token tag">token punctuation"><artifactIdtoken punctuation">>jjwt-impltoken tag">token tag">token punctuation"></artifactIdtoken punctuation">>token tag">token tag">token punctuation"><versiontoken punctuation">>0.12.5token tag">token tag">token punctuation"></versiontoken punctuation">>token tag">token tag">token punctuation"></dependencytoken punctuation">>token tag">token tag">token punctuation"><dependencytoken punctuation">>token tag">token tag">token punctuation"><groupIdtoken punctuation">>io.jsonwebtokentoken tag">token tag">token punctuation"></groupIdtoken punctuation">>token tag">token tag">token punctuation"><artifactIdtoken punctuation">>jjwt-jacksontoken tag">token tag">token punctuation"></artifactIdtoken punctuation">>token tag">token tag">token punctuation"><versiontoken punctuation">>0.12.5token tag">token tag">token punctuation"></versiontoken punctuation">>token tag">token tag">token punctuation"></dependencytoken punctuation">>

2、创建Jwt工具类

java">token comment">/*** jwt工具类*/
token annotation punctuation">@Slf4j
token keyword">public token keyword">class token class-name">JwtUtil token punctuation">{token keyword">private token keyword">static token keyword">final token class-name">String SECRET token operator">= token string">"yhzy"token punctuation">; token comment">// 密钥:可任意字符串token keyword">private token keyword">static token keyword">final token keyword">long defaultExpire token operator">= token number">1000 token operator">* token number">60 token operator">* token number">60 token operator">* token number">24 token operator">* token number">7Ltoken punctuation">;token comment">//过期时间:7天token comment">//创建一个jwt密钥 加密和解密都需要用这个玩意token keyword">private token keyword">static token keyword">final token class-name">SecretKey key token operator">= token class-name">Jwtstoken punctuation">.SIGtoken punctuation">.HS256token punctuation">.token function">keytoken punctuation">(token punctuation">)token punctuation">.token function">randomtoken punctuation">(token keyword">new token class-name">SecureRandomtoken punctuation">(SECRETtoken punctuation">.token function">getBytestoken punctuation">(token class-name">StandardCharsetstoken punctuation">.UTF_8token punctuation">)token punctuation">)token punctuation">)token punctuation">.token function">buildtoken punctuation">(token punctuation">)token punctuation">;token keyword">private token class-name">JwtUtiltoken punctuation">(token punctuation">) token punctuation">{token punctuation">}token comment">/*** 使用默认过期时间(7天),生成一个JWT** @param claims   JWT中的数据* @return*/token keyword">public token keyword">static token class-name">String token function">createTokentoken punctuation">( token class-name">Maptoken generics">token punctuation"><token class-name">Stringtoken punctuation">, token class-name">Objecttoken punctuation">> claimstoken punctuation">) token punctuation">{token keyword">return token function">createTokentoken punctuation">(claimstoken punctuation">, defaultExpiretoken punctuation">)token punctuation">;token punctuation">}token comment">/*** 生成token** @param claims   请求体数据* @param expire   过期时间 单位:毫秒* @return token*/token keyword">public token keyword">static token class-name">String token function">createTokentoken punctuation">(token class-name">Maptoken generics">token punctuation"><token class-name">Stringtoken punctuation">, token class-name">Objecttoken punctuation">> claimstoken punctuation">, token class-name">Long expiretoken punctuation">) token punctuation">{token class-name">JwtBuilder builder token operator">= token class-name">Jwtstoken punctuation">.token function">buildertoken punctuation">(token punctuation">)token punctuation">;token class-name">Date now token operator">= token keyword">new token class-name">Datetoken punctuation">(token punctuation">)token punctuation">;token comment">// 生成tokenbuildertoken punctuation">.token function">issuertoken punctuation">(token string">"yhzy.fun"token punctuation">) token comment">//签发者token punctuation">.token function">claimstoken punctuation">(claimstoken punctuation">) token comment">//数据token punctuation">.token function">issuedAttoken punctuation">(nowtoken punctuation">) token comment">//签发时间token punctuation">.token function">expirationtoken punctuation">(token keyword">new token class-name">Datetoken punctuation">(nowtoken punctuation">.token function">getTimetoken punctuation">(token punctuation">) token operator">+ expiretoken punctuation">)token punctuation">) token comment">//过期时间token punctuation">.token function">signWithtoken punctuation">(keytoken punctuation">)token punctuation">; token comment">//签名方式buildertoken punctuation">.token function">headertoken punctuation">(token punctuation">)token punctuation">.token function">addtoken punctuation">(token string">"JWT"token punctuation">, token string">"JSpWdhuPGblNZApVclmX"token punctuation">)token punctuation">;token keyword">return buildertoken punctuation">.token function">compacttoken punctuation">(token punctuation">)token punctuation">;token punctuation">}token comment">/*** 解析token** @param token jwt token* @return Claims*/token keyword">public token keyword">static token class-name">Claims token function">parseTokentoken punctuation">(token class-name">String tokentoken punctuation">) token punctuation">{token keyword">try token punctuation">{token keyword">return token class-name">Jwtstoken punctuation">.token function">parsertoken punctuation">(token punctuation">)token punctuation">.token function">verifyWithtoken punctuation">(keytoken punctuation">)  token comment">//密钥token punctuation">.token function">buildtoken punctuation">(token punctuation">) token punctuation">.token function">parseSignedClaimstoken punctuation">(tokentoken punctuation">) token punctuation">.token function">getPayloadtoken punctuation">(token punctuation">)token punctuation">;token punctuation">} token keyword">catch token punctuation">(token class-name">Exception etoken punctuation">) token punctuation">{token keyword">if token punctuation">(e token keyword">instanceof token class-name">ExpiredJwtExceptiontoken punctuation">) token punctuation">{token comment">// 判断JWT是否过期了 如果过期会抛出ExpiredJwtException异常token keyword">throw token keyword">new token class-name">JwtVerificationExceptiontoken punctuation">(token string">"token已过期"token punctuation">)token punctuation">;token punctuation">}token keyword">if token punctuation">(e token keyword">instanceof token class-name">JwtExceptiontoken punctuation">) token punctuation">{token keyword">throw token keyword">new token class-name">JwtVerificationExceptiontoken punctuation">(token string">"token已失效"token punctuation">)token punctuation">;token punctuation">}logtoken punctuation">.token function">infotoken punctuation">(token string">"jwt解析失败" token operator">+ etoken punctuation">)token punctuation">;token keyword">throw token keyword">new token class-name">JwtVerificationExceptiontoken punctuation">(token string">"token解析失败"token punctuation">)token punctuation">;token punctuation">}token punctuation">}
token punctuation">}

3、测试:生成token 和解析 token ,也可以通过在线工具解析测试:https://tooltt.com/jwt-decode

java">token annotation punctuation">@SpringBootTest
token keyword">class token class-name">ApplicationTests token punctuation">{token comment">//生成tokentoken annotation punctuation">@Testtoken keyword">void  token function">createJwtTesttoken punctuation">(token punctuation">)token punctuation">{token comment">//创建一个Map对象,将数据封装到Map中,并生成tokentoken class-name">Maptoken generics">token punctuation"><token class-name">Stringtoken punctuation">, token class-name">Objecttoken punctuation">> claims token operator">= token class-name">Maptoken punctuation">.token function">oftoken punctuation">(token string">"id"token punctuation">, token number">1token punctuation">, token string">"username"token punctuation">, token string">"yhzy"token punctuation">)token punctuation">;token comment">//调用工具类生成tokentoken class-name">String tokentoken operator">=token class-name">JwtUtiltoken punctuation">.token function">createTokentoken punctuation">(claimstoken punctuation">)token punctuation">;token class-name">Systemtoken punctuation">.outtoken punctuation">.token function">printlntoken punctuation">(tokentoken punctuation">)token punctuation">;token punctuation">}token comment">//解析tokentoken annotation punctuation">@Testtoken keyword">void  token function">parseJwtTesttoken punctuation">(token punctuation">)token punctuation">{token comment">//解析token:将生成的Token进行解析token class-name">String tokentoken operator">=token string">"eyJKV1QiOiJKU3BXZGh1UEdibE5aQXBWY2xtWCIsImFsZyI6IkhTMjU2In0.eyJpc3MiOiJ5aHp5LmZ1biIsImlkIjoxLCJ1c2VybmFtZSI6InloenkiLCJpYXQiOjE3Mjk2NzUxODIsImV4cCI6MTczMDI3OTk4Mn0.R828xZjAAof-KOMxppTtZkqL58TbDwgXUeG9fCTM-RA"token punctuation">;token class-name">Claims claims token operator">= token class-name">JwtUtiltoken punctuation">.token function">parseTokentoken punctuation">(tokentoken punctuation">)token punctuation">; token comment">//解析tokentoken class-name">Systemtoken punctuation">.outtoken punctuation">.token function">printlntoken punctuation">(claimstoken punctuation">)token punctuation">;token punctuation">}
token punctuation">}

http://www.ppmy.cn/ops/129419.html

相关文章

安全见闻8-9

声明 学习视频来自B站UP主泷羽sec,如涉及侵权马上删除文章 笔记的只是方便各位师傅学习知识,以下网站只涉及学习内容,其他的都与本人无关,切莫逾越法律红线,否则后果自负 安全见闻8&#xff1a;量子计算 一&#xff0c;量子计算原理概述&#xff1a; 量子概念的产生&#xf…

Navict的入门使用

目录 Navicat主页面 功能简介​编辑 连接数据库 Navicat 连接 MySQL 数据库 数据库备份 Navicat主页面 功能简介 连接数据库 Navicat 连接 MySQL 数据库 使用 Navicat 连接 MySQL 数据库是一个相对简单的过程。以下是详细的步骤&#xff1a; 1. 下载并安装 Navicat 首先…

C++基础:vector

在编写程序之前&#xff0c;我们首先要准备好相关的数据。比如说需要准备好一组电话号码&#xff0c;一球队的队员表&#xff0c;一个课表等关于这些相同类型的数据&#xff0c;C语言是通过数组来实现的。 int arry[10] {0,1,2,3,4,5,6,7,8,9};而在C当中处理这类数据是通过vec…

C#自定义事件的案例

方法一&#xff0c;详细的声明 namespace HelloWorldConsole {internal class Program{static void Main(string[] args){Customer customer new Customer();Waiter waiter new Waiter();customer.Order waiter.Action;customer.Action();}}public class OrderEventArgs : …

用Rust从头写CAD】第一章 Rust基础 第二节 第一个Rust程序

文章目录 [TOC](文章目录) 1、新建名称为“cad”的项目2、编辑器打开名称为“cad”的项目3、使用编辑器4、运行程序 Rust自带管理工具cargo&#xff0c;它让我们新建项目更加便捷。 1、新建名称为“cad”的项目 请在文件夹中选择项目的主目录 如上图&#xff0c;我选的路径是…

设计模式(一)

设计模式&#xff08;一&#xff09; 特点&#xff1a;可复用的面向对象软件 底层思维 设计者 抽象思维语言构造 面向对象 编译转换 组件封装 内存模型 设计模式 运行状态 架构模式封装&#xff1a;隐藏…

2024年网络安全(黑客)自学总结

前言 什么是网络安全 网络安全可以基于攻击和防御视角来分类&#xff0c;我们经常听到的 “红队”、“渗透测试” 等就是研究攻击技术&#xff0c;而“蓝队”、“安全运营”、“安全运维”则研究防御技术。 如何成为一名黑客 很多朋友在学习安全方面都会半路转行&#xff0c…

docker 安装 PostgreSQL

参考链接 https://hub.docker.com/_/postgres 安装 # 后台运行&#xff0c;镜像名称为 postgres # --name postgres 容器名称为 postgres # POSTGRES_PASSWORD 超级用户的密码&#xff0c;超级用户名默认为&#xff1a;postgres&#xff0c;可以使用 POSTGRES_USER 环境变量设…