当前位置: 首页 > article >正文

SpringMVC根据url校验权限,防止垂直越权

思路是加一个拦截器,对除登录接口的所有请求进行拦截。拦截到请求后,查询当前用户都拥有哪些url的权限(这个需要权限表有url字段),然后与当前请求的url对比,如果相同则说明有权限,否则没有。

首先配置拦截器

1、创建拦截器类,及重要参数:

public class PermissionInterceptor implements HandlerInterceptor {

    private List<String> excludeUrls;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }

    public List<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }
}

2、打开spring-mvc.xml文件,在里面加上拦截器配置:

<mvc:interceptor>
  <mvc:mapping path="/**" />
  <bean class="com.xxx.interceptor.PermissionInterceptor">
    <property name="excludeUrls">
      <list>
        <value>loginController.do?login</value>
        <value>loginController.do?logout</value>
      </list>
    </property>
  </bean>
</mvc:interceptor>

然后开始写代码

主要逻辑代码如下:

public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;
    @Resource
    private ClientManager clientManager;

    private List<String> excludeUrls;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过转换,获取用户的请求URL地址
        String requestPath = ResourceUtil.getAuthRequsetPath(request);

        //针对拦截器排除URLS,进行排除
        if (excludeUrls.contains(requestPath)) {
            return true;
        }
        Client client = clientManager.getClient(ContextHolderUtils.getSession().getId());
        TSUser currLoginUser = client != null ? client.getUser() : null;
        if (currLoginUser != null ) {
            String loginUserName = currLoginUser.getUserName();
            String loginUserId = currLoginUser.getId();
            // 如果是管理员,则无需校验权限
            if("admin".equals(loginUserName)){
                return true;
            }
            // 取请求url问号前的部分
            String requestPathPrefix = StringUtils.split(requestPath, '?')[0];
            if (systemService.loginUserIsHasUrlAuth(requestPathPrefix, loginUserId)) {
                return true;
            }
            forwardTimeOut(request, response);
            return false;
        } else {
            forwardTimeOut(request, response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }

    /**
     * 跳转: 登录超时页面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void forwardTimeOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.sendRedirect(request.getSession().getServletContext().getContextPath()+"/webpage/login/timeout.jsp");
    }

    public List<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }
}

获取requestPath方法代码:

public static String getAuthRequsetPath(HttpServletRequest request) {
    String queryString = request.getQueryString();
    String requestPath = request.getRequestURI();
    if (StringUtils.isNotEmpty(queryString)) {
      requestPath += "?" + queryString;
    }
    if (requestPath.indexOf("&") > -1) {/
      requestPath = requestPath.substring(0, requestPath.indexOf("&"));
    }
    if (requestPath.indexOf("=") != -1) {
      if (requestPath.indexOf(".do") != -1) {
        requestPath = requestPath.substring(0, requestPath.indexOf(".do") + 3);
      }
      else {
        requestPath = requestPath.substring(0, requestPath.indexOf("?"));
      }
    }
    requestPath = requestPath.substring(request.getContextPath().length() + 1);
    return requestPath;
  }

loginUserIsHasUrlAuth()方法代码:

public boolean loginUserIsHasUrlAuth(String requestPathPrefix, String userid) {
  String functionurlLike = requestPathPrefix + "%";
  String sql = "SELECT count(*) FROM t_function f, t_role_function  rf,t_role_user ru " +
  " WHERE f.id=rf.functionId AND rf.roleId=ru.roleId AND " +
  "ru.userId=? AND f.functionUrl like ?";
  Long authSize = this.getCountForJdbcParam(sql, userid, functionurlLike);
  return authSize > 0;
}

这样就可以了。


http://www.kler.cn/a/500671.html

相关文章:

  • Python对象的序列化和反序列化工具:Joblib与Pickle
  • C# XPTable 日期字段处理(XPTable控件使用说明十三)
  • 电池预测 | 第21讲 基于Gamma伽马模型结合EM算法和粒子滤波算法参数估计的锂电池剩余寿命预测
  • nvim 打造成可用的IDE(2)
  • 如何看待Akamai 退出中国市场进行转型?
  • 【2024年华为OD机试】 (A卷,100分)- 租车骑绿岛(Java JS PythonC/C++)
  • Leetcode 3418. Maximum Amount of Money Robot Can Earn
  • 23_Spring Boot中Redis缓存实现
  • web服务器快速目录搜索遍历工具推荐:Dirsearch
  • 正向传播和反向传播的理解
  • 页面滚动下拉时,元素变为fixed浮动,上拉到顶部时恢复原状,js代码以视频示例
  • 2025华数杯国际赛A题完整论文讲解(含每一问python代码+数据+可视化图)
  • Scratch编程:点燃编程学习热情的火种
  • ElasticsearchJavaClient工具类分享
  • Ubuntu 磁盘修复
  • 图像处理中实现 C++ 和 Python 的高效通信——Boost.Interprocess mmap
  • 【Uniapp-Vue3】插槽Slots及具名插槽实现组件高度定制化
  • [SAP ABAP] APPEND INITIAL LINE 追加空行
  • 苍穹外卖08——(涉及接收日期格式数据、ApachePOI导出报表、sql获取top10菜品数据)
  • doris:模型注意事项
  • npm 与 pnpm:JavaScript 包管理工具的对比与选择
  • 泛目录和泛站有什么差别
  • 跳表和Mysql联合索引的最左原则和索引下推的优化
  • 禅道使用实践(2)-产品篇
  • Golang笔记——rune和byte
  • Linux 容器漏洞