Jwt登录认证(拦截器):
使用拦截器统一验证令牌
登录和注册接口需要放行
interceptors.LoginInterceptor:(注册一个拦截器)
- package com.lin.springboot01.interceptors;
-
- import com.lin.springboot01.pojo.Result;
- import com.lin.springboot01.utils.JwtUtil;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
-
- import java.util.Map;
-
- @Component
- public class LoginInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- String token = request.getHeader("Authorization");
- try {
- //能否解析成功
- Map
claims = JwtUtil.parseToken(token); - //放行
- return true;
- } catch (Exception e) {
- //解析失败,httpServletResponse响应码设置为401
- response.setStatus(401);
- return false;
- }
- }
- }
config.WebConfig:(在config配置项中配置拦截器)
- package com.lin.springboot01.config;
-
- import com.lin.springboot01.interceptors.LoginInterceptor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.validation.annotation.Validated;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
- @Autowired
- private LoginInterceptor loginInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //登录接口和注册接口不拦截
- registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login","/user/register");
- }
- }
controller.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
list(/*@RequestHeader(name = "Authorization") String token, HttpServletResponse response*/){ - //验证token
- /* try {
- Map
claims = JwtUtil.parseToken(token); //parseToken是JwtUtil工具类里定义的解析token的方法 - return Result.success("可以展示数据");
- } catch (Exception e) {
- response.setStatus(401);
- return Result.error("未登录");
- }*/
- return Result.success("可以展示数据");
- }
-
- }

