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

Spring Boot Security配置问题:除/welcome外全路由需认证却出现重定向循环

问题原因

出现ERR_TOO_MANY_REDIRECTS无限重定向的核心问题是:

  • 你只开放了/welcome登录页的匿名访问权限,但登录请求的默认处理路径POST /login没被允许匿名访问。用户在/welcome提交登录表单时,请求会发往/login,这个路径被/**规则拦截要求认证,于是又被重定向回/welcome,形成循环。
  • 未明确配置登录成功后的跳转路径,默认逻辑可能加剧重定向冲突。
修正后的配置
@Configuration
public class AppConfig {

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeHttpRequests(auth -> auth
                        // 开放登录页和登录提交路径的匿名访问
                        .requestMatchers("/welcome", "/login").permitAll()
                        // 其余所有路径必须认证
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        // 指定自定义登录页
                        .loginPage("/welcome")
                        // 登录成功后强制跳转到根路径
                        .defaultSuccessUrl("/", true)
                        // 可选:登录失败后返回登录页并携带错误标识
                        .failureUrl("/welcome?error=true")
                )
                .httpBasic();
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
关键配置说明
  • 新增/login到permitAll:解决登录提交请求被拦截的问题,打破重定向循环。
  • defaultSuccessUrl("/", true):第二个参数设为true,表示无论用户之前访问的是哪个受保护路径,登录成功后都直接跳转到根路径/,完全符合你的需求。
  • 用anyRequest().authenticated()替代requestMatchers("/**").authenticated():这是Spring Security官方推荐的写法,语义更明确,避免路径匹配优先级问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:40:22