Springboot使用登录拦截器LoginInteceptor来做登录认证
创建拦截器LoginInteceptor类
interceptors/LoginInteceptor.java
package org.example.interceptors;import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import java.util.Map;@Component // 注册为bean
public class LoginInteceptor implements HandlerInterceptor {// 拦截器逻辑@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 获取请求头中的tokenString token = request.getHeader("Authorization");// 验证tokentry {Map<String, Object> claims = JwtUtil.parseToken(token); // 解析tokenreturn true; // 放行} catch (Exception e) {// http响应码为401response.setStatus(401);return false; // 拦截}}
}
注册拦截器
config/WebConfig.java
package org.example.config;import org.example.interceptors.LoginInteceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration // 注册为bean
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate LoginInteceptor loginInterceptor;// 放行登录接口和注册接口@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "/user/register");}
}
使用
controller/ArticleController.java
package org.example.controller;import org.example.pojo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/article")
public class ArticleController {@RequestMapping("/list")public Result<String> list() {return Result.success("获取文章列表成功");}
}