springsecurity出现重定向次数过多

最近在使用springsecurity时,出现了以下问题
在这里插入图片描述

1、.anyRequest() .authenticated();

http.formLogin()
               .loginPage("/login.html")
               .loginProcessingUrl("/api/private/login")
               .defaultSuccessUrl("/success.html")
               .and()
               .authorizeRequests()
               .anyRequest()
               .authenticated();

原因是我们使用了这个
.anyRequest() .authenticated(),它的意思是任何请求都需要进行登录认证,当跳转到/login.html时,由于login.html也是请求,它会让login.html进行认证,所以会再次访问login.html,所以就造成了无限循环进行重定向。

解决方法


 http.formLogin()
               .loginPage("/login.html")
               .loginProcessingUrl("/api/private/login")
               .defaultSuccessUrl("/success.html")
               .and()
               .authorizeRequests()
               .antMatchers("/login.html").permitAll()
               .anyRequest()
               .authenticated();
               .and().csrf().disable();

其中的.and().csrf().disable(); csrf(跨站请求伪造)也可以理解为防火墙;如果没关闭,当你登录时,它虽然不会出现重定向次数过多的情况,但也会回到login.html页面

当然重定向次数过多也有其他情况,本质上都是访问login.html,然后又让login.html进行认证,结果就是陷入访问死循环