Проблема с несколькими WebSecurityConfigurerAdapter при весенней загрузке - PullRequest
0 голосов
/ 02 октября 2018

Я использую spring-boot-1.5.10 и spring-boot-starter-security.В моем микросервисе я открываю API для внешнего мира и внутренних микросервисов.так что я бы хотел 2 вида безопасности.один для внешних вызовов и другой для внутренних вызовов.

Я ссылался на этот URL и пытался внедрить несколько адаптеров безопасности в моем приложении.Но не повезло, он всегда выбирает внутренний вместо внешнего,

Пожалуйста, найдите адаптер безопасности для вашей справки,

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired(required = false)
    ServiceWebSecurityConfigurer serviceWebSecurityConfigurer;

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web
//                .ignoring()
//                .antMatchers(HttpMethod.PUT,"/v1/emp/**")
//                .antMatchers(HttpMethod.DELETE,"/v1/emp/**");
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authenticationProvider(new ExternalApiAuthenticationProvider())
                .securityContext()
                .securityContextRepository(new ExternalApiSecurityContextRepository())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new ApiAuthenticationEntrypoint())
                .and()
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/v1/**").fullyAuthenticated();
        if(serviceWebSecurityConfigurer != null)
            serviceWebSecurityConfigurer.configure(http);
        http.authenticationProvider(new InternalApiAuthenticationProvider())
            .securityContext()
            .securityContextRepository(new InternalApiSecurityContextRepository())
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(new ApiAuthenticationEntrypoint())
            .and()
            .httpBasic().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.PUT,"/v1/emp/**").fullyAuthenticated()
            .antMatchers(HttpMethod.DELETE,"/v1/emp/**").fullyAuthenticated();
    }
}

Он всегда выбирает "InternalApiSecurityContextRepository", даже если внешний API используетвнутренняя безопасность.Кажется, что последний переопределяет первый.

ОБНОВЛЕНИЕ-1 (согласно ответу Гаурава Шривастава)

Внешний адаптер безопасности вызовов API:

@EnableWebSecurity
public class WebSecurityConfig {

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authenticationProvider(new InternalApiAuthenticationProvider())
                .securityContext()
                .securityContextRepository(new InternalApiSecurityContextRepository())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new InternalApiAuthenticationEntrypoint())
                .and()
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.PUT,"/v1/emp/**").fullyAuthenticated()
                .antMatchers(HttpMethod.DELETE,"/v1/emp/**").fullyAuthenticated();
        }
    }

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authenticationProvider(new ExternalApiAuthenticationProvider())
                .securityContext()
                .securityContextRepository(new ExternalApiSecurityContextRepository())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new ApiAuthenticationEntrypoint())
                .and()
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/v1/**").fullyAuthenticated();
        }
    }
}

Он работает для внешнего (поскольку порядок равен 1), но для внутреннего мы получаем следующее исключение и используем контекст безопасности внешней конфигурации:

Произошла внутренняя ошибка сервера. Сообщение: AnОбъект аутентификации не найден в SecurityContext

Я думаю, что проблема здесь в том, что мы не можем использовать контекст 2-безопасности, как кажется. Есть ли в любом случае другой контекст безопасности?

ЛюбойНамек был бы действительно заметен, чтобы решить проблемуЗаранее спасибо.

1 Ответ

0 голосов
/ 02 октября 2018

Вы задаете более одной конфигурации и задаете порядок с помощью аннотации @Order.

Внутренняя конфигурация со своим собственным поставщиком аутентификации и шаблоном URL.

@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Configuration
    @Order(1)
    public static class InternalSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/internal/**")
                .authorizeRequests().anyRequest().hasRole("ADMIN")
                .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint());
        }


    .
    @Configuration
        @Order(2)
        public static class ExternalSecurityConfig extends WebSecurityConfigurerAdapter {
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/external/**")
                    .authorizeRequests().anyRequest().hasRole("ADMIN")
                    .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint());
            }


        }

Получите более подробную информацию с помощьюстатья ниже.https://www.baeldung.com/spring-security-multiple-entry-points

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