Spring Security 6中/**/*.js模式失效,Spring Boot3迁移遇PatternParse错误
Spring Boot 3(Spring Security 6)路径模式
/**/*.x的替代方案 问题根源
Spring Security 6默认采用PathPatternParser替代了旧版的AntPathMatcher,PathPattern语法中,通配符**只能作为路径的最后一部分(比如/static/**是合法的),而/**/*.js这种在中间插入**的模式不再被支持,因此会触发PatternParse错误。
替代方案
方案1:使用官方静态资源匹配工具(推荐)
Spring Security提供了PathRequest.toStaticResources()工具类,专门用于匹配静态资源,既符合PathPattern规范,又能覆盖常见的静态资源类型(如图片、CSS、JS、HTML等)。
修改后的代码示例:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().ignoringRequestMatchers("/api/**").and() .authorizeHttpRequests(authorize -> authorize .shouldFilterAllDispatcherTypes(true) .dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll() .requestMatchers( "/", "/api/v1/links/**", "/_admin/**", "/swagger-ui.html*", "/swagger-resources/**", "/webjars/springfox-swagger-ui/**", "/swagger-resources", "/api-docs/**", "/api/**", "/login", "/login/**", "/oauth2/**", "/static/**", "/404", "/405", "/favicon.ico", "/demoLink/**", "/DemoLink/**", "/templateLink/**" ).permitAll() // 替换原有后缀匹配,自动匹配常见静态资源 .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() .anyRequest().authenticated() ) .oauth2Login(); http.headers().httpStrictTransportSecurity().maxAgeInSeconds(0); return http.build(); }
如果需要精确指定允许的资源后缀,可以单独声明:
.requestMatchers( PathRequest.toStaticResources().withExtension("png"), PathRequest.toStaticResources().withExtension("gif"), PathRequest.toStaticResources().withExtension("svg"), PathRequest.toStaticResources().withExtension("jpg"), PathRequest.toStaticResources().withExtension("html"), PathRequest.toStaticResources().withExtension("css"), PathRequest.toStaticResources().withExtension("js") ).permitAll()
方案2:自定义RequestMatcher匹配URI后缀
如果需要更灵活的匹配逻辑,可以通过Lambda表达式自定义RequestMatcher,直接判断请求URI的后缀:
.authorizeHttpRequests(authorize -> authorize // ... 其他配置 .requestMatchers(request -> { String uri = request.getRequestURI(); return uri.endsWith(".png") || uri.endsWith(".gif") || uri.endsWith(".svg") || uri.endsWith(".jpg") || uri.endsWith(".html") || uri.endsWith(".css") || uri.endsWith(".js"); }).permitAll() // ... 其他配置 )
方案3:回退到AntPathMatcher(不推荐)
如果需要完全兼容旧版路径模式,可以配置Spring Security使用AntPathMatcher,但官方不推荐此方案——PathPattern性能更优,是未来的标准规范。
配置方式:
- 声明全局
PathMatcherBean:
@Bean public PathMatcher pathMatcher() { return new AntPathMatcher(); }
- 在
SecurityFilterChain中使用antMatchers替代requestMatchers:
.authorizeHttpRequests(authorize -> authorize // ... 其他配置 .antMatchers( "/", // ... 其他路径 "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js" ).permitAll() // ... 其他配置 )
内容的提问来源于stack exchange,提问作者Bassem
相关产品推荐
相关产品推荐

