Spring Security — порядок фильтров и несколько HttpSecurity

Я хочу, чтобы две разные конфигурации http входили в зависимости от URL-адреса, который я ввожу. Например, когда я ввожу «localhost:8080/HQ/test_web», я хочу, чтобы эта конфигурация появилась.

 @Configuration
    @Order(1)
    public static class FirstWaveFilters extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/HQ/test_web/**").anonymous().and().addFilterBefore(new CustomFilter(),BasicAuthenticationFilter.class);

        }
    }

Но, если это что-то еще, я хочу, чтобы эта конфигурация пришла:

@Configuration
    @Order(2)
    public static class SecondWaveFilters extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and().csrf().disable().authorizeRequests()
                    .antMatchers("/h2-console/**").permitAll()

                    .antMatchers("/webjars/**").permitAll()



                    .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                    .anyRequest().authenticated()
                    .and()

                    .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                    .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                    // this disables session creation on Spring Security
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            http.authorizeRequests().antMatchers("/**").permitAll();

            http.csrf().disable();
            http.headers().frameOptions().disable();
        }
    }

Я настроил их в том же классе, что и в документе Spring Security:

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    private UserDetailsServiceImpl userDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(UserDetailsServiceImpl userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Configuration
    @Order(1)
    public static class FirstWaveFilters extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/HQ/test_web/**").anonymous().and().addFilterBefore(new CustomFilter(),BasicAuthenticationFilter.class);

        }
    }
    @Configuration
    @Order(2)
    public static class SecondWaveFilters extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and().csrf().disable().authorizeRequests()
                    .antMatchers("/h2-console/**").permitAll()

                    .antMatchers("/webjars/**").permitAll()



                    .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                    .anyRequest().authenticated()
                    .and()

                    .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                    .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                    // this disables session creation on Spring Security
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            http.authorizeRequests().antMatchers("/**").permitAll();

            http.csrf().disable();
            http.headers().frameOptions().disable();
        }
    }

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

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

Но, похоже, это не работает. Какой бы URL я ни вводил, вызывается только CUSTOMFILTER(), поэтому только первая конфигурация. В основном то, чего я пытаюсь достичь, это то, что если пользователь вводит первый URL-адрес, я хочу, чтобы customfilter() был фильтром, через который должен пройти запрос, если это любой другой URL-адрес, я хочу, чтобы он прошел вторую конфигурацию и два фильтры, определенные там как те, через которые должен пройти запрос. Почему это не работает?

0
1
1 144
1

Ответы 1

http.antMatcher(...) - значит применить это http и все что здесь настроено при выполнении шаблона в antMatcher.

http.authorizeRequests()... - определяет ваши разрешения, если пользователь попал в эту конечную точку, он должен иметь «АДМИН», «зарегистрированный» и т. д.


В вашем FirstWaveFilters вы должны начать свой http с http.antMatcher():

http.antMatcher("/HQ/test_web/**");
http.authorizeRequests().antMatchers("/HQ/test_web/**").anonymous()
   .and()
   .addFilterBefore(new CustomFilter(),BasicAuthenticationFilter.class);

Если вы не добавите http.antMatcher(...);, то http перехватит все URL-адреса и SecondWaveFilters никогда не будет достигнут.

http.authorizeRequests().antMatchers("/HQ/test_web/**").anonymous() - означает, что любой анонимный пользователь может нажать /HQ/test_web/**, но здесь не сказано «применить FirstWaveFilters, когда /HQ/test_web/**», это просто означает, что любой, кто шипит /HQ/test_web/**, может быть анонимным.

Другие вопросы по теме