SpringBoot-用户登录拦截,Cookies验证,全局用户变量设置

1、创建拦截器

@Component
public class SignInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(SignInterceptor.class);
    @Autowired
    private TUserService userService;

    /**
     * 预处理回调方法,实现处理器的预处理
     * 返回值:true表示继续流程;false表示流程中断,不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.info("SignInterceptor开始拦截.........");
        Cookie[] cookies = request.getCookies();
        String session = null;
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("sessionId")) {
                    session = cookie.getValue();
                }
            }
        }
        // 判断sessionId是否有效
        TUser tUser = userService.checkSession(session);
        if(tUser == null){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSONObject.toJSON(ActionResult.errorResponse(CodeEnum.LOGIN_ERR.getCode(),CodeEnum.LOGIN_ERR.getMsg())));
            return false;
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(tUser,null);
        authentication.setDetails(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return true;
    }

    /**
     * 后处理回调方法,实现处理器(controller)的后处理,但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }
    /**
     * 整个请求处理完毕回调方法,即在视图渲染完毕时回调,
     * 如性能监控中我们可以在此记录结束时间并输出消耗时间,
     * 还可以进行一些资源清理,类似于try-catch-finally中的finally,
     * 但仅调用处理器执行链中
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}

2、增加拦截器配置文件

public class MvcInterceptorConfig extends WebMvcConfigurationSupport {

    @Autowired
    private SignInterceptor signInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则,/**表示拦截所有请求
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(signInterceptor)
                .addPathPatterns("/api/user/**")
                .addPathPatterns("/api/record/**")
                .excludePathPatterns("/api/user/register");
        super.addInterceptors(registry);
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        // 增加跨域设置
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3088")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowCredentials(true)
                .allowedHeaders("*")
                .maxAge(3600);
        super.addCorsMappings(registry);
    }
}

3、获取全局变量

// 获取登录用户ID
    public Integer getLoginUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TUser user = (TUser) authentication.getPrincipal();
        logger.info("BaseController getLoginUserId -> userId:{}",user.getId());
        return user.getId();
    }

4、cookies设置

// 登录成功设置Cookies
Cookie cookie = new Cookie("cookiesName",cookies);
cookie.setPath("/");
cookie.setMaxAge(24 * 60 * 60);
response.addCookie(cookie);

 

你可能感兴趣的:(SpringBoot)