SpringSecurity创建了301和302重定向到登录页面的无限循环

eimct9ow  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(484)

我有一个springboot2.0.4.release的应用程序,其中有些url是公共的,有些则需要身份验证。它工作得很好,但是当我用这个工具检查它时->https://www.redirect-checker.org/ 当我查看我的主页或任何子页面时:

Result
https://www.myurl.com/
    302 
    https://www.myurl.com/index
    302 
    http://www.myurl.com/index
    301 Moved Permanently
    https://www.myurl.com/index
    302 
    https://www.myurl.com/index
    302 
    http://www.myurl.com/index
    301 Moved Permanently
    https://www.myurl.com/index
    302 
    https://www.myurl.com/index
    302 
    http://www.myurl.com/index
    301 Moved Permanently
    https://www.myurl.com/index

...
以下是我的配置:

@Configuration
@EnableWebSecurity
@EnableAutoConfiguration
@EnableScheduling
public class ApplicationConfig extends WebSecurityConfigurerAdapter {

private static final String[] GET_PUBLIC_URLS = {
            "/",
            "/resources/**",
            ...
    };
    private static final String[] POST_PUBLIC_URLS = {
            "/password_reset",
            ...
    };

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers(GET, GET_PUBLIC_URLS).permitAll()
                .antMatchers(POST, POST_PUBLIC_URLS).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        //do nothing
                    }
                })
                .loginPage("/index")
                .usernameParameter("email")
                .defaultSuccessUrl("/user_account", true)
                .and()
                .logout()
                .permitAll();
    }
...
}

我还在application.config中添加了其他设置

server.tomcat.protocol-header=x-forwarded-proto
server.use-forward-headers=true

总的来说,这就是我在stackoverflow上所能找到的解决问题的方法,但是我仍然有重定向问题。我是不是漏了什么?

kyvafyod

kyvafyod1#

好的,配置不正确。这里有一个很好的例子:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers(GET, GET_PUBLIC_URLS).anonymous()
                .antMatchers(POST, POST_PUBLIC_URLS).anonymous()
                .and()
                .formLogin()
                .loginPage("/index")
                .usernameParameter("email")
                .defaultSuccessUrl("/user_account", true)
                .and()
                .logout()
                .permitAll();
    }

问题是公共URL对所有人都是公共的,因此.anyrequest().authenticated()不正确,在我的例子中应该是匿名的()。

相关问题