Spring Security с несколькими страницами входа занимает только порядок 1 - PullRequest
1 голос
/ 17 июня 2020

У меня есть приложение Spring Boot, в котором страница входа будет в индексе (nav), а также на странице входа. Я выполнил конфигурацию аннотации заказа, однако она работает только так, как ожидалось, порядок 1 (проверено путем переключения порядка, и 1 работает только нормально) Для ошибки порядка 2: метод запроса 'POST' не поддерживается, есть идея?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Qualifier("userDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Configuration
    @Order(1)
    public static class WebSecurityConfig1 extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(new AntPathRequestMatcher("/**"))
                    .authorizeRequests()
                    .antMatchers("/resources/**", "/registration", "/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/loginIndex")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .failureUrl("/loginIndex?error")
                    .loginProcessingUrl("/loginIndex")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll();
        }
    }
    @Configuration
    @Order(2)
    public static class WebSecurityConfig2 extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(new AntPathRequestMatcher("/**"))
                    .authorizeRequests()
                    .antMatchers("/resources/**", "/registration","/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .failureUrl("/login?error")
                    .loginProcessingUrl("/login")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll();
        }
    }

    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

1 Ответ

1 голос
/ 17 июня 2020

Проблема в вашей конфигурации

  1. WebSecurityConfig1 и WebSecurityConfig2 оба настроены для сопоставления всех URL-адресов. . ie new AntPathRequestMatcher("/**")
  2. Это означает, что @Order(1) всегда будет удовлетворять все запросы.

Решение

Итак, сначала вам нужно чтобы решить, для каких URL-адресов вы хотите, чтобы пользователь был перенаправлен на первую страницу входа и для каких URL-адресов вы хотите, чтобы пользователь был перенаправлен на вторую страницу входа.

Например, вы можете сказать, что URL-адреса, начинающиеся с /user, идут на loginPage("/loginIndex") а все остальное идет на loginPage("/login"). Вы можете добиться этого, заменив new AntPathRequestMatcher("/**") на (new AntPathRequestMatcher("/user*")) в WebSecurityConfig1

...