You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.1.1中Spring Security与MVC视图权限规则配置问题

解决方案与原理分析

正确配置方案

使用MvcRequestMatcher结合HandlerMappingIntrospector配置权限规则,仅针对Spring MVC请求路径做校验,无需单独配置JSP物理路径。示例代码如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
        // 基于MVC映射构建请求匹配器
        MvcRequestMatcher.Builder mvcMatcher = new MvcRequestMatcher.Builder(introspector);

        http
            .authorizeHttpRequests(auth -> auth
                // 放行登录相关路径
                .requestMatchers(mvcMatcher.pattern("/login*")).permitAll()
                // 要求/test路径需拥有TEST权限
                .requestMatchers(mvcMatcher.pattern("/test")).hasAuthority("TEST")
                // 其他所有请求需认证
                .anyRequest().authenticated()
            )
            // 配置表单登录(根据实际需求调整)
            .formLogin(form -> form.permitAll());

        return http.build();
    }
}

原理说明

  1. 问题根源
    你遇到的403错误,是因为默认的AntPathRequestMatcher会拦截所有请求——包括Controller处理后内部转发到JSP的请求。当访问/test时,DispatcherServlet处理完成后会转发到/WEB-INF/view/test.jsp,这个转发请求会再次经过Spring Security过滤器链,而你未给该JSP路径配置权限,因此触发403。

  2. MvcRequestMatcher的作用
    MvcRequestMatcher是Spring Security专为Spring MVC设计的请求匹配器,它基于Spring MVC的请求映射元数据(即Controller中定义的@RequestMapping路径)进行匹配,只会识别客户端发起的MVC请求路径,不会匹配内部转发的物理资源路径(如JSP文件路径)。因此,配置/test的权限规则后,内部转发到JSP的请求不会被该匹配器拦截,自然无需额外配置JSP路径的权限。

  3. WEB-INF资源的安全性
    /WEB-INF目录下的资源本身就无法被客户端直接访问,只能通过服务器内部转发访问,因此不需要为这些路径配置权限规则。使用MvcRequestMatcher恰好契合这一特性,避免了重复配置的问题。

内容的提问来源于stack exchange,提问作者ko4evneg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:27:00