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

Spring Boot 3及以上版本如何配置permitAll匿名访问?

Spring Boot 3.0.0 配置匿名访问(permitAll)的正确方式

问题原因

Spring Boot 3.0.x 对应 Spring Security 6.x,原WebSecurityCustomizer的.ignoring()逻辑在新版本中匹配规则有变化,且直接忽略路径会绕过Spring Security全量过滤器(包括CORS、CSRF等),容易导致配置失效或引发安全风险。更推荐通过SecurityFilterChain配置匿名访问。

修正后的配置代码

方案一:通过SecurityFilterChain配置permitAll(推荐)

将需要匿名访问的路径在authorizeHttpRequests中声明为permitAll(),替代原WebSecurityCustomizer的忽略逻辑:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .csrf(CsrfConfigurer::disable)
        .authorizeHttpRequests(requests -> requests
            // 配置允许匿名访问的路径
            .requestMatchers("/actuator/**", "/graphiql/**", "/voyager/**", "/vendor/**", "/rest/**",
                             "/swagger-ui/**", "/v3/api-docs/**")
            .permitAll()
            // 其余所有路径需认证
            .anyRequest().authenticated())
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
        .build();
}

// 仅保留预检请求的忽略逻辑(若需处理CORS)
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return web -> web.ignoring().requestMatchers(CorsUtils::isPreFlightRequest);
}

方案二:仍使用WebSecurityCustomizer(不推荐)

如果坚持使用路径忽略,需适配Spring Security 6.x的匹配规则,显式指定Ant风格匹配器:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return web -> web
        .ignoring()
        .requestMatchers(CorsUtils::isPreFlightRequest)
        .requestMatchers(AntPathRequestMatcher.antMatcher("/actuator/**"))
        .requestMatchers(AntPathRequestMatcher.antMatcher("/graphiql/**"))
        .requestMatchers(AntPathRequestMatcher.antMatcher("/voyager/**"))
        .requestMatchers(AntPathRequestMatcher.antMatcher("/vendor/**"))
        .requestMatchers(AntPathRequestMatcher.antMatcher("/rest/**"))
        .requestMatchers(AntPathRequestMatcher.antMatcher("/swagger-ui/**"))
        .requestMatchers(AntPathRequestMatcher.antMatcher("/v3/api-docs/**"));
}

关键说明

  • 优先选方案一:通过SecurityFilterChain配置permitAll(),能保证目标路径仍经过Spring Security过滤器链(如CORS处理),既允许匿名访问,又保持安全可控。
  • 路径匹配规则:Spring Security 6.x默认使用PathPatternParser,若需Ant风格匹配,需显式调用AntPathRequestMatcher.antMatcher()。
  • 预检请求处理:CORS预检请求(OPTIONS方法)可通过WebSecurityCustomizer忽略,也可在authorizeHttpRequests中添加requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:40:21