springboot + vue-admin-template 拦截器校验JWT

拦截器代码

获取 token 需要判断请求:

  • /getUserInfo 获取用户请求,是在 url 后面携带 token 参数
  • 其他请求,是在 header 中携带 token 参数
package com.stdspringboot.interceptor;

import com.stdspringboot.util.Constant;
import com.stdspringboot.util.JWTUtil;
import com.stdspringboot.util.ResponseUtils;
import com.stdspringboot.vo.JsonResult;
import com.stdspringboot.vo.UserInfoJWT;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInter implements HandlerInterceptor {

    //方法controller前,先经过该方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method=request.getMethod();
        String uri=request.getRequestURI();
        System.out.println(uri+"--"+method);
        //跨域会发送 OPTIONS 请求,该请求header中没有auth,直接放行
        if("OPTIONS".equals(method)){
            return true;
        }
        String auth=null;
        if("/getUserInfo".equals(uri)){
            auth=request.getParameter(Constant.JWT_TOKEN);
        }else{
            auth=request.getHeader(Constant.JWT_TOKEN2);
        }

        System.out.println("jwt token:"+auth);

        //发请求时,没携带 JWT,给出提示信息
        if(auth==null || "".equals(auth)){
            String json=JsonResult.fail(JsonResult.CODE_NO_LOGIN,"请先登录!").toJSON();
            ResponseUtils.writeJSON(response,json);
            return false;
        }
        try {
            //解析
            UserInfoJWT uij = JWTUtil.parse(auth, UserInfoJWT.class);//校验 JWT,并解析数据
        }catch (Exception e){
            e.printStackTrace();
            //验证、解析失败,说明携带 JWT 数据不正确,给出提示信息
            JsonResult jr=JsonResult.fail(JsonResult.CODE_NO_LOGIN,"请先登录!");
            ResponseUtils.writeJSON(response,jr.toJSON());
            return false;
        }
        //校验登录通过
        return true;
    }
}

配置类

import com.stdspringboot.interceptor.LoginInter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

//配置类必须加此注解,否则不生效
@Configuration
public class SpringBootConfig implements WebMvcConfigurer {

    @Resource
    private LoginInter loginInter;

    //添加拦截器,通过形参注册拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInter) // 推荐使用 springboot同一管理创建,并注入
                .addPathPatterns("/**")  // 拦截所有路径
                .excludePathPatterns(  //登录页面、注册页面、js、登录、注册的controller都不拦截
                        "/login",
                        "/reg",
                        "/noLogin",
                        "/favicon.ico");
    }


    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

}

原文出处:https://www.malaoshi.top/show_1IX34Mpu4dsC.html