springboot整合springsecurity时出现了localhost将您重定向次数过多 循环地址错误解决

如图,在重定向页面时发生了地址循环的现象,错误是重定向次数过多

 查看代码,为了跳转到我们自己定义的登录页面,写了loginPage("/login.html"),按照正常的逻辑,应该我们在访问接口的时候,都会跳到登录页面,结果却报错了。其原因是我们在访问接口时,因为有 anyRequest(),对所有的请求都要进行认证,所以会跳到login.html这个页面,跳转过去之后去请求login.html这个页面也需要身份认证,所以还是跳到了login.html这个页面,形成了死循环,所以会出现这个错误。

 protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义自己编写的登录页面
            .loginPage("/login.html")  //登录页面设置
            .loginProcessingUrl("/user/login") //登录访问设置
            .defaultSuccessUrl("/test/index")  //登录成功之后,跳转路径
            .failureForwardUrl("/login.html")
            .and().authorizeRequests()
                  .antMatchers("/user/index").permitAll() //设置哪些路径可以直接访问不需要认证
            .anyRequest().authenticated()//除以上之外都需要认证
            .and().csrf().disable();//关闭csrf保护
    }

解决方式:在其中加上.antMatchers("/login.html").permitAll() ,在这个方法里添加的url是不需要进行身份认证的,如果以后有更多的页面需要加入,只需要以逗号隔开就行

 protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //自定义自己编写的登录页面
            .loginPage("/login.html")  //登录页面设置
            .loginProcessingUrl("/user/login") //登录访问设置
            .defaultSuccessUrl("/test/index")  //登录成功之后,跳转路径
            .failureForwardUrl("/login.html")
            .and().authorizeRequests()
                  .antMatchers("/login.html","/test/hello","/user/index").permitAll() //设置哪些路径可以直接访问不需要认证
            .anyRequest().authenticated()//除以上之外都需要认证
            .and().csrf().disable();//关闭csrf保护
    }

这样就解决了!

猜你喜欢

转载自blog.csdn.net/JSUITDLWXL/article/details/128427526