使用Spring Security自定义登录页面时出现ERR_TOO_MANY_REDIRECTS错误,请求排查问题
排查ERR_TOO_MANY_REDIRECTS错误的解决方案
看起来你遇到了典型的循环重定向问题,结合你的代码,我梳理了两个最可能的原因和对应的解决办法:
1. 重复的/login路径映射导致冲突
你同时在WebConfig中通过addViewController("/login")注册了登录页面的视图控制器,又在Controller中用@GetMapping("/login")处理同一个路径。这会让Spring MVC在处理/login请求时出现歧义,可能触发不必要的重定向循环。
解决办法:
移除WebConfig中addViewController("/login")这部分代码,只保留Controller中的GetMapping来处理/login请求,这样就能确保请求统一由你的Controller处理,同时正确注入ModelMap数据:
// WebConfig.java 中删除以下代码 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("home"); }
2. 登录页面加载前的服务调用需要认证
你的Controller的login方法中调用了ldapAuthConfigService.getEnabledAuthentications(),如果这个方法(或者它内部调用的其他方法)被添加了@PreAuthorize等需要认证的注解(因为你开启了@EnableGlobalMethodSecurity(prePostEnabled = true)),那么在匿名用户访问/login页面时,调用这个方法会触发Spring Security的认证拦截,重定向回/login页面,形成无限循环。
解决办法:
- 检查并调整方法权限:查看
ldapAuthConfigService.getEnabledAuthentications()方法是否有认证注解,如果有,添加@PreAuthorize("permitAll()")允许匿名访问:@PreAuthorize("permitAll()") public List<String> getEnabledAuthentications() { // 你的实现代码 } - 显式允许/login匿名访问:在Security配置中,显式将/login加入允许匿名的规则(虽然formLogin的loginPage已经设置了permitAll,但显式声明可以避免规则顺序导致的问题):
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() // 显式允许/login匿名访问 .antMatchers("/**").authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/layout", true) .and() .logout() .clearAuthentication(true) .invalidateHttpSession(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .permitAll() .and() .authenticationProvider(customeAuthenticationProvider()); // ... 其他配置 }
验证步骤
- 先移除WebConfig中的重复视图控制器配置,测试是否解决问题。
- 如果仍有循环,检查ldapAuthConfigService的方法权限,确保获取authType的操作不需要认证。
- 最后调整Security的规则顺序,确保/login优先被允许匿名访问。
内容的提问来源于stack exchange,提问作者Anjana
相关产品推荐
相关产品推荐

