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

Spring Boot 3升级后自定义登录页出现重定向循环问题求助

问题根源

你的重定向循环是因为Mvc路由转发规则与Spring Security认证规则冲突:

  • Spring Security配置中,/需要认证,会重定向到允许匿名访问的/login
  • 但你的Mvc配置将/login请求转发到了/,导致/login访问后又回到需要认证的/,触发新一轮重定向,形成循环。
修复方案

1. 调整Mvc路由转发规则

移除将/login转发到/的配置,让/login直接映射到static目录下的登录页面。修改MvcConfig示例:

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 直接将/login映射到登录视图,而非转发到/
        registry.addViewController("/login").setViewName("forward:/login.html");
        // 保留根路径行为:访问/时重定向到/login
        registry.addViewController("/").setViewName("redirect:/login");
    }
}

2. 修正Spring SecurityFilterChain配置

确保请求匹配规则准确,明确登录页及处理路径:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/static/**", "/login", "/userAuth").permitAll()
            .anyRequest().authenticated()
        )
        .formLogin(form -> form
            .loginPage("/login") // 指定自定义登录页路径
            .loginProcessingUrl("/userAuth") // 登录处理接口路径
            .defaultSuccessUrl("/home", true) // 登录成功后跳转路径
            .permitAll()
        )
        .logout(logout -> logout.permitAll());
    return http.build();
}

3. 验证静态资源访问

确认Spring Boot正确识别static目录资源,可在application.properties中明确配置:

spring.web.resources.static-locations=classpath:/static/
关键说明

Spring Boot 3.x中Spring Security弃用了WebSecurityConfigurerAdapter,改为基于SecurityFilterChain的配置,核心是保证请求匹配顺序和规则的准确性。同时需避免Mvc路由规则与Security认证规则形成循环依赖,确保登录页的访问不会触发需要认证的路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:18:17