后端拦截器

package com.huoziqi.springboot.common.config;

import com.huoziqi.springboot.common.handler.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器
 * @version 1.0
 * @Author 作者名
 * @Date 2022/10/21 22:29
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("[idea] =====>> 拦截一次");
        // 在@Configration注解生效时不会爆红
        // 拦截所有请求判断token是否合法决定是不是要登录
        
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login","/register","/file/upload")
                .excludePathPatterns("/user/export","/login/**","/file/**");
    }


}

登录拦截

 1 /**
 2  * 拦截器功能
 3  * 对token进行验证
 4  */
 5 //@Component
 6 public class LoginInterceptor implements HandlerInterceptor {
 7 
 8     @Resource
 9     UserMapper userMapper;
10 
11     @Override
12     public boolean preHandle(HttpServletRequest request,
13                              HttpServletResponse response,
14                              Object handler) throws Exception {
15 
16         //如果不是映射到方法直接通过
17         if(!( handler instanceof HandlerMethod)){
18             return true;
19         }
20 
21         //获取前端传递过来的token
22         String token = request.getHeader("token");
23         System.out.println("token_is" + token);  //================================
24 
25         // token非空校验
26         if(StringUtils.isBlank(token)){
27             throw new ServiceExceptin(Constans.CODE_401,"没有token 请重新登录");
28         }
29 
30         // 根据token获取id进行验证
31 
32         Map<String, Object> map = JWTUtils.checkToken(token);
33 
34         Integer id =(Integer) map.get("userId");
35 
36         User user = userMapper.selectById(id);
37 
38         // user存到UserThreadLocal
39         UserThreadLocal.put(user);
40 
41         if(user == null){
42             throw new ServiceExceptin(Constans.CODE_401,"登陆过期,重新登录");
43         }
44 
45 
46         /**
47          * 登陆拦截逻辑
48          * 前端请求路径时判断token
49          * token == null  不放行
50          * token != null 放行
51          * 通过token验证user信息合法性
52          * user == null 重新登录,可能是token过期了
53          * user != null 放行
54          */
55         return true;
56     }
57 }

 

 

posted on 2023-05-21 17:36  你就学个JVAV?  阅读(19)  评论(0)    收藏  举报

导航