当前位置:网站首页>JWT操作工具类分享
JWT操作工具类分享
2022-06-26 20:08:00 【菜鸟是大神】
分享一下个人操作 JWT
的工具类。基于 jjwt
库,这是一个Java圈子最流行的 JWT
操作库。
TIPS
jjwt
GitHub:GitHub - jwtk/jjwt: Java JWT: JSON Web Token for Java and Android- 本工具类来自个人开源的认证、授权框架 Light Security
加依赖
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.10.7</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.10.7</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.10.7</version> <scope>runtime</scope> </dependency>
工具类:
@Slf4j @RequiredArgsConstructor @SuppressWarnings("WeakerAccess") @Component public class JwtOperator { /** * 秘钥 * - 默认aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt */ @Value("${secret:aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt}") private String secret; /** * 有效期,单位秒 * - 默认2周 */ @Value("${expire-time-in-second:1209600}") private Long expirationTimeInSecond; /** * 从token中获取claim * * @param token token * @return claim */ public Claims getClaimsFromToken(String token) { try { return Jwts.parser() .setSigningKey(this.secret.getBytes()) .parseClaimsJws(token) .getBody(); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) { log.error("token解析错误", e); throw new IllegalArgumentException("Token invalided."); } } /** * 获取token的过期时间 * * @param token token * @return 过期时间 */ public Date getExpirationDateFromToken(String token) { return getClaimsFromToken(token) .getExpiration(); } /** * 判断token是否过期 * * @param token token * @return 已过期返回true,未过期返回false */ private Boolean isTokenExpired(String token) { Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } /** * 计算token的过期时间 * * @return 过期时间 */ private Date getExpirationTime() { return new Date(System.currentTimeMillis() + this.expirationTimeInSecond * 1000); } /** * 为指定用户生成token * * @param claims 用户信息 * @return token */ public String generateToken(Map<String, Object> claims) { Date createdTime = new Date(); Date expirationTime = this.getExpirationTime(); byte[] keyBytes = secret.getBytes(); SecretKey key = Keys.hmacShaKeyFor(keyBytes); return Jwts.builder() .setClaims(claims) .setIssuedAt(createdTime) .setExpiration(expirationTime) // 你也可以改用你喜欢的算法 // 支持的算法详见:https://github.com/jwtk/jjwt#features .signWith(key, SignatureAlgorithm.HS256) .compact(); } /** * 判断token是否非法 * * @param token token * @return 未过期返回true,否则返回false */ public Boolean validateToken(String token) { return !isTokenExpired(token); } public static void main(String[] args) { // 1. 初始化 JwtOperator jwtOperator = new JwtOperator(); jwtOperator.expirationTimeInSecond = 1209600L; jwtOperator.secret = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt"; // 2.设置用户信息 HashMap<String, Object> objectObjectHashMap = Maps.newHashMap(); objectObjectHashMap.put("id", "1"); // 测试1: 生成token String token = jwtOperator.generateToken(objectObjectHashMap); // 会生成类似该字符串的内容: eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ System.out.println(token); // 将我改成上面生成的token!!! String someToken = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ"; // 测试2: 如果能token合法且未过期,返回true Boolean validateToken = jwtOperator.validateToken(someToken); System.out.println(validateToken); // 测试3: 获取用户信息 Claims claims = jwtOperator.getClaimsFromToken(someToken); System.out.println(claims); // 将我改成你生成的token的第一段(以.为边界) String encodedHeader = "eyJhbGciOiJIUzI1NiJ9"; // 测试4: 解密Header byte[] header = Base64.decodeBase64(encodedHeader.getBytes()); System.out.println(new String(header)); // 将我改成你生成的token的第二段(以.为边界) String encodedPayload = "eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk1NDEsImV4cCI6MTU2Njc5OTE0MX0"; // 测试5: 解密Payload byte[] payload = Base64.decodeBase64(encodedPayload.getBytes()); System.out.println(new String(payload)); // 测试6: 这是一个被篡改的token,因此会报异常,说明JWT是安全的 jwtOperator.validateToken("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk3MzIsImV4cCI6MTU2Njc5OTMzMn0.nDv25ex7XuTlmXgNzGX46LqMZItVFyNHQpmL9UQf-aUx"); } }
写配置
jwt: secret: 秘钥 # 有效期,单位秒,默认2周 expire-time-in-second: 1209600
使用:
@Autowired private JwtOperator jwtOperator; // ...
边栏推荐
猜你喜欢
数据库范式和主码的选择
[recommended collection] these 8 common missing value filling skills must be mastered
Project practice 6: distributed transaction Seata
【推荐收藏】这8个常用缺失值填充技巧一定要掌握
抖音实战~搜索页面~视频详情
Basic and necessary common plug-ins of vscade
Some cold knowledge about QT database development
stm32和电机开发(直流有刷电机和步进电机)
Disruptor本地线程队列_使用transProcessor处理器和WorkPool两种方式进行消费对比---线程间通信工作笔记005
MySQL - table creation and management
随机推荐
抖音实战~首页视频~下拉刷新
网上开户万一免五到底安不安全?
[recommended collection] these 8 common missing value filling skills must be mastered
浏览器的垃圾回收机制
Development of NFT for digital collection platform
抖音实战~分享模块~生成短视频二维码
Uni app uses canvas to draw QR code
关于不等式取值转义的思路
Pinda general permission system (day 1~day 2)
mongoDB的三种基础备份方法
Jsonutils tool class (based on Alibaba fastjson)
Request method 'POST' not supported
[MySQL series] collection of common working SQL (continuous update)
项目实战六:分布式事务-Seata
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
案例描述:比赛分数管理系统,需要统计历届冠军所得比赛得分,并记录到文件中,其中系统有如下需求:- 打开系统有欢迎界面,并显示可选择的选项- 选项1:记录比赛得分- 选项2:查看往届
710. random numbers in the blacklist
Reading notes: process consulting III
Selection of database paradigm and main code
Guomingyu: Apple's AR / MR head mounted display is the most complicated product in its history and will be released in January 2023