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

Spring Security 6中如何添加permitAll()?适配Spring Security 5配置改写

Spring Security 6 配置实现 permitAll()

你需要用authorizeHttpRequests()替代Spring Security 5中的authorizeRequests(),并在其中配置请求的权限规则,permitAll()就放在对应的请求匹配器之后。以下是完整的等价配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .csrf(CsrfConfigurer::disable)
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/").permitAll()
            .anyRequest().authenticated() // 和原Spring Security 5配置默认行为一致,其他路径需认证
        );
    return http.build();
}

说明:

  • csrf(CsrfConfigurer::disable):和原配置的csrf().disable()作用完全一致,禁用CSRF防护。
  • authorizeHttpRequests(auth -> ...):这是Spring Security 6中配置权限规则的入口,替代了旧版的authorizeRequests()。
  • requestMatchers("/").permitAll():指定根路径"/"允许所有用户访问,对应原配置的antMatchers("/").permitAll()。
  • .anyRequest().authenticated():这是Spring Security的默认行为(原配置也隐含该规则),即除明确允许的路径外,其他所有请求都需要认证。如果业务不需要此规则可去掉,但建议保留以保证安全性。

如果只想让当前过滤器链处理根路径请求,也可以结合securityMatchers配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .securityMatchers(matchers -> matchers.requestMatchers("/"))
        .csrf(CsrfConfigurer::disable)
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/").permitAll()
        );
    return http.build();
}

这种写法下,只有"/"路径会被该过滤器链处理,其他请求不会经过此链的安全校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:32:40