首页 > 编程语言 > SpringBoot登录用户权限拦截器
2021
03-22

SpringBoot登录用户权限拦截器

1. 创建自定义拦截器类并实现 HandlerInterceptor 接口

package com.xgf.online_mall.interceptor;

import com.xgf.online_mall.system.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@Slf4j
@Component
public class UserLoginAuthInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info(" ======== UserAuthInterceptor preHandle 登录权限拦截器拦截");
    User user = (User) request.getSession().getAttribute("loginUser");
    //未登录才判断,登录了直接放行
    if(user == null){
      //获取访问路径
      String address = request.getRequestURI();
      log.info("======== 拦截,访问路径 address : {}", address);
      response.sendRedirect(request.getContextPath() + "/login.html");
      return false;

      /*String address = request.getRequestURI();
      log.info("======== 拦截,访问路径 address : {}", address);
      //不是登录或者注册页面,就直接跳转登录界面
      if(!address.contains("login") && !address.contains("register")){
        //强制到登录页面
        response.sendRedirect(request.getContextPath() + "/login.html");
        //设置为false,不访问controller
        return false;
      }*/
    }
    //其它模块或者已经登录,就直接放行
//    log.info("======== 已登录 user = {}", user);
    return true;
  }


  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    log.info(" ===== UserAuthInterceptor postHandle");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    log.info("==== UserAuthInterceptor afterCompletion");

    //记录日志 向文件里面写日志
    //获取服务器记录日志log文件所存放的目录位置 -- tomcat下的真实路径+log目录
    String logdir = request.getServletContext().getRealPath("log");
    //路径不存在就创建
    Path logdirPath = Paths.get(logdir);
    if(Files.notExists(logdirPath)){
      Files.createDirectories(logdirPath);
    }
    //目录存在就将数据[字符]写入 //存放日志的路径+文件名
    Path logfile = Paths.get(logdir,"userlog.log");
    //logfile.toFile() paths转换为File类型 true以追加的方式写入
    BufferedWriter writer = new BufferedWriter(new FileWriter(logfile.toFile(),true));

    //获取登录用户信息
    User user = (User)request.getSession().getAttribute("loginUser");
    //记录user信息,存入日志
    writer.write(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " >> " + user +"\r\n");
    writer.flush();
    writer.close();
  }
}

2. 创建WebMvcConfigurer接口实现类,注册并生效自定义的拦截器

import com.xgf.online_mall.constant.PathConstantParam;
import com.xgf.online_mall.interceptor.UserLoginAuthInterceptor;
import lombok.extern.slf4j.Slf4j;
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;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class LoginConfig implements WebMvcConfigurer {
  @Autowired
  private UserLoginAuthInterceptor userLoginAuthInterceptor;

  /**
   * addInterceptors方法设置拦截路径
   *   addPathPatterns:需要拦截的访问路径
   *   excludePathPatterns:不需要拦截的路径,
   *   String数组类型可以写多个用","分割
   * @param registry
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry){
    log.info(" ======== LoginConfig.addInterceptors");
    //添加对用户未登录的拦截器,并添加排除项
    //error路径,excludePathPatterns排除访问的路径在项目中不存在的时候,
    //springboot会将路径变成 /error, 导致无法进行排除。
    registry.addInterceptor(userLoginAuthInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns("/js/**", "/css/**", "/img/**", "/plugins/**")
        .excludePathPatterns("/login.html", "/register.html", "/system/user/login", "/system/user/login", "/index")
        .excludePathPatterns("/error");
  }
 }

到此这篇关于SpringBoot登录用户权限拦截器的文章就介绍到这了,更多相关SpringBoot 用户权限拦截器内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧