Springboot使用jwt实现登录认证
文章目录
- 一、登录认证
- 二、JWT简介
- 三、使用JWT
- pom.xml引入起步依赖
- 编写工具类JwtUtil
- 单元测试类JwtTest
- 使用
- 效果
- 四、参考资料
一、登录认证
令牌就是一段字符串
承载业务数据, 减少后续请求查询数据库的次数
防篡改, 保证信息的合法性和有效性
二、JWT简介
三、使用JWT
pom.xml引入起步依赖
<!--java jwt坐标--><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.4.0</version></dependency>
编写工具类JwtUtil
utils/JwtUtil.java
package com.devops.utils;import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;import java.util.Date;
import java.util.Map;public class JwtUtil {private static final String KEY = "devops";//接收业务数据,生成token并返回public static String genToken(Map<String, Object> claims) {return JWT.create().withClaim("claims", claims).withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12)).sign(Algorithm.HMAC256(KEY));}//接收token,验证token,并返回业务数据public static Map<String, Object> parseToken(String token) {return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token).getClaim("claims").asMap();}}
单元测试类JwtTest
package org.example;import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.util.Date;
import java.util.HashMap;
import java.util.Map;@SpringBootTest
public class JwtTest {// 生成加密后的token@Testpublic void testGen() {Map<String, Object> claims = new HashMap<>();claims.put("id", 1);claims.put("username", "张三");// 生成jwt代码String token = JWT.create().withClaim("user", claims) // 添加载荷.withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12)) // 设置过期时间.sign(Algorithm.HMAC256("itheima")); // 指定算法,生成密钥System.out.println(token);}// 验证加密后的token@Testpublic void testVerify() {String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3NDU2ODE2ODd9" +".IJ8x-hbz5b9kvdu2rah-iI0rQ8CuD4FYxA4OWdqUaNI";try {DecodedJWT decodedJWT =JWT.require(Algorithm.HMAC256("itheima")).build().verify(token);Map<String, Claim> claims = decodedJWT.getClaims();System.out.println(claims.get("user"));} catch (Exception e) {System.out.println("验证失败");}}
}
使用
//使用JwtUtil工具类生成tokenMap<String, Object> claims = new HashMap<>();claims.put("id", user.getId());claims.put("username", username);String token = JwtUtil.genToken(claims);return Result.success(token);
效果
四、参考资料
https://www.bilibili.com/video/BV14z4y1N7pg?spm_id_from=333.788.player.switch&vd_source=0467ab39cc5ec5940fee22a0e7797575&p=19