当前位置:网站首页>JWT(JSON Web Token)的基础使用
JWT(JSON Web Token)的基础使用
2022-07-19 05:02:00 【ID_云泽】
组成:
JWT由三个部分组成,头部(Header)、载荷(Payload)、签名(Signature),如:xxxx.yyyy.zzzz
例:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyQWNjb3VudCI6ImFkbWluIiwiZXhwIjoxNjIzNzcxNjk3LCJ1c2VySWQiOiIxMjMifQ.2W2F0Xz4-DV8O-awQHOaAUgCZWz0ZvIVnpljsfSdAqs
使用方式:
1. 在maven中添加jwt的依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
2. 创建jwt的工具类,里面一个方法用于生成token,一个用于校验token
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gh.common.service.JwtUtils;
import java.util.Date;
import java.util.HashMap;
/** * @author gaohan * @version 1.0 * @date 2021/3/24 23:49 */
public class JwtUtilsImpl implements JwtUtils {
/** * 用户token的过期时间为一天 * TODO 正式上线更换为120分钟 */
private final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
/** * token私钥 */
private final String TOKEN_SECRET = "18067f08-f06d-4bb1-8db8-35d02116f7ff";
/** * 生成签名,一段时间后后过期 * * @param userAccount 账号 * @param userId 用户id * @return */
@Override
public String sign(String userAccount, String userId) {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
//私钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头信息
HashMap<String, Object> header = new HashMap<>(2);
header.put("typ", "JWT");
header.put("alg", "HS256");
//附带userAccount和userID生成签名
return JWT.create().withHeader(header).withClaim("userAccount", userAccount)
.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
}
@Override
public boolean verity(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
}
3. 测试
public static void main(String[] args) throws Exception {
JwtUtilsImpl jwt = new JwtUtilsImpl();
String token = jwt.sign("admin", "123");
System.err.println("token:" + token);
boolean verity_1 = jwt.verity(token);
System.err.println("verity_1:" + verity_1);
boolean verity_2 = jwt.verity(token.substring(0, token.length() - 1));
System.err.println("verity_2:" + verity_2);
}
边栏推荐
猜你喜欢
太卷了, 某公司把自家运营多年的核心系统(智慧系统)完全开源了....
Next time, the interviewer will ask about the design of high concurrency system and directly dump this article to him
Etcd database source code analysis -- etcdserver run apply process
.NET 全场景开发终于到来了
Unityvr robot Scene 1 setup scene
PC网站实现微信扫码登录功能(二)
Problems encountered in execve execution - resolved
MaixHub在线训练初体验
Rllib学习[2] --env定义 + env rollout
C#使用Objects Comparer进行对象比较
随机推荐
下次面试官再问高并发系统设计,直接把这篇文章甩给他
After SQL grouping, get the whole record of the row with the maximum or minimum value of one of the fields
Flask框架——数据库配置及迁移同步
中国碳碳复合材料市场调研与投资预测报告(2022版)
UnityVR-机械臂场景1-搭建场景
Codeforces 429E 2-SAT
China ambroxol market forecast and investment strategy report (2022 Edition)
Tkinter module GUI Graphical programming practice (VIII) -- Chinese chess (including super detailed and complete source code, free download link of complete program)
基于.NET动态编译技术实现任意代码执行
升级PHP8中踩到的坑
STM32 SCT memory control
TCP与UDP的区别
Rock paper will develop ar game for San Diego priest baseball team
Basic knowledge about coding table
CacheManager - 用 C# 编写的 .NET 的开源缓存抽象层
SQL 时间拼接问题,系统自动截断的拼接复原
如何区分固态硬盘和机械硬盘
Kuzaobao: summary of Web3 encryption industry news on July 18
Bootloader learning notes - Part 2
sql分组后获取其中一个字段最大值或最小值的该行的整条记录