备注说明:
用户登录成功后,系统会自动下发JWT令牌,然后在后续的每次请求中,浏览器都需要在请求头header中携带到服务器,请求头的名称为Authorization,值为登录时下发的JWT令牌。
如果检测到用户未登录,则http相应状态码为401
JwtUtil
package com.lin.springboot01.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 = "liner2332";//接受业务数据,生成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();}
}
ArticleController
package com.lin.springboot01.controller;import com.lin.springboot01.pojo.Result;
import com.lin.springboot01.utils.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Map;@RestController
@RequestMapping("/article")
public class ArticleController {@GetMapping("/list")public Result<String> list(@RequestHeader(name = "Authorization") String token, HttpServletResponse response){//验证tokentry {Map<String, Object> claims = JwtUtil.parseToken(token); //parseToken是JwtUtil工具类里定义的解析token的方法return Result.success("可以展示数据");} catch (Exception e) {response.setStatus(401);return Result.error("未登录");}}
}
先用注册登录接口,拿到用户token。
再把data中的token数据,拿到list接口放到请求头Autorization中进行验证