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

Spring Boot新版本SecurityConfig无WebSecurityConfigurerAdapter配置异常

问题:新版Spring Security不继承WebSecurityConfigurerAdapter时的权限配置问题

本人正在学习Spring课程,教授使用旧版Spring Boot,而我采用新版开发,在不继承WebSecurityConfigurerAdapter实现SecurityConfig时遇到问题:访问http://localhost:8080/h2-console/正常,但访问其他路径时返回403 Forbidden错误。根据课程内容,访问非h2-console路径时,浏览器应跳转至登录页,Postman应返回401 Unauthorized,请问需如何修改才能达到预期效果?

教授的旧版示例代码

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] PUBLIC_MATCHERS = { "/h2-console/**" };

    @Autowired
    private Environment env;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
            http.headers().frameOptions().disable();
        }

        http.cors().and().csrf().disable();
        http.authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated();

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

我的新版实现代码

@EnableWebSecurity
@Configuration
public class SecurityConfig  {
    private static final String[] PUBLIC_MATCHERS = {"/h2-console/**"};

    @Autowired
    private Environment env;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //desliga a protecao a csrf, o que permite executar metodos POST,PUT,DELETE sem sessao de usuario
        http.authorizeHttpRequests().requestMatchers(PathRequest.toH2Console()).permitAll().and().headers().frameOptions().disable(); //libera acesso ao h2-console
        http.cors();

        return http.build();
    }
}

问题原因与解决方案

问题分析

你的新版代码存在两个关键缺失:

  1. 没有明确要求所有非公开路径必须认证,导致Spring Security默认拒绝所有未明确允许的请求,返回403
  2. 未配置认证入口(如表单登录、HTTP Basic认证),即使要求认证,也无法引导浏览器跳转登录页,或给API工具返回401

修改后的完整代码

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级权限控制,和教授代码保持一致
public class SecurityConfig  {
    @Autowired
    private Environment env;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 针对test环境禁用frameOptions,适配h2-console
        if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
            http.headers().frameOptions().disable();
        }

        http.csrf().disable() // 禁用CSRF,适配无状态请求
            .cors() // 启用CORS
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话
            .and()
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(PathRequest.toH2Console()).permitAll() // 允许h2-console访问
                .anyRequest().authenticated() // 所有其他路径必须认证
            )
            .formLogin() // 配置表单登录,浏览器访问时跳转默认登录页
            .and()
            .httpBasic(); // 配置HTTP Basic认证,Postman等工具访问时返回401 Unauthorized

        return http.build();
    }
}

关键修改点说明

  • 添加@EnableGlobalMethodSecurity(prePostEnabled = true):启用@PreAuthorize等方法级权限注解,和教授的旧版代码功能对齐
  • 补充anyRequest().authenticated():明确所有非h2-console的路径都需要认证
  • 配置formLogin():为浏览器提供登录入口,未认证时自动跳转至Spring Security默认登录页
  • 配置httpBasic():为Postman等API调用工具提供HTTP Basic认证支持,未认证时返回401 Unauthorized
  • 恢复了旧版代码中针对test环境禁用frameOptions的逻辑,确保h2-console在测试环境正常显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:12:49