Spring Security - упорядочение фильтров и множественная HttpSecurity - PullRequest
0 голосов
/ 19 марта 2019

Я хочу, чтобы две разные 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, я хочу, чтобы он прошел вторую конфигурацию иФильтры, определенные там, чтобы быть теми, через которые должен пройти запрос.Почему это не работает?

1 Ответ

0 голосов
/ 20 марта 2019

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

http.authorizeRequests()... - определяет ваши разрешения, если пользователь нажал на эту конечную точку, он должен иметь «ADMIN», «logged» и т. Д.


В вашем 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/**, может быть анонимным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...