Аннотации методов безопасности с конфигурацией Java и Spring Security 3.2

У меня возникли проблемы с настройкой приложения с помощью аннотации на уровне метода, контролируемой@EnableGlobalMethodSecurity Я использую Servlet 3.0 стиль инициализации с помощью

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(MultiSecurityConfig.class);
    }
}

Я попытался 2 разных способа инициализацииAuthenticationManager оба со своими проблемами. Обратите внимание, чтоне с помощью@EnableGlobalMethodSecurity приводит к успешному запуску сервера, и вся защита формы выполняется должным образом. Мои проблемы возникают, когда я добавляю@EnableGlobalMethodSecurity а также@PreAuthorize("hasRole('ROLE_USER')") аннотации на моем контроллере.

Я пытаюсь настроить безопасность на основе форм и API. Аннотации на основе методов должны работать только для обеспечения безопасности API.

Одна конфигурация была следующей.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**").httpBasic();
        }

        protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
        }
    }

    @Configuration
    public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/static/**","/status");
        }

        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().hasRole("USER").and()
                .formLogin().loginPage("/login").permitAll();
        }

        protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
        }
    }

}

Это не идеально, так как я действительно хочу только одну регистрацию механизма аутентификации, но главная проблема заключается в том, что это приводит к следующему исключению:

java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []

Насколько я знаю@EnableGlobalMethodSecurity устанавливает свой собственныйAuthenticationManager так что я'Я не уверен, что проблема здесь.

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

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MultiSecurityConfig {

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return new AuthenticationManagerBuilder(ObjectPostProcessor.QUIESCENT_POSTPROCESSOR)
                .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER").and()
                    .withUser("admin").password("password").roles("USER", "ADMIN").and()
                    .and()
                .build();
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        @Override protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**").httpBasic();
        }
    }

    @Configuration
    public static class FormWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/static/**","/status");
        }

        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().hasRole("USER").and()
                .formLogin().loginPage("/login").permitAll();
        }
    }

}

Этот конфиг действительно запускается успешно, но с исключением

java.lang.IllegalArgumentException: A parent AuthenticationManager or a list of AuthenticationProviders is required
at org.springframework.security.authentication.ProviderManager.checkState(ProviderManager.java:117)
at org.springframework.security.authentication.ProviderManager.(ProviderManager.java:106)
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.performBuild(AuthenticationManagerBuilder.java:221)

и когда я проверяю, я обнаружил, что безопасность нея работаю

я смотрю на это уже пару дней и даже после погружения в код реализации весенней безопасности я могуКажется, я не понял, что не так с моей конфигурацией.

Я использую spring-security-3.2.0.RC1 и spring-framework-3.2.3.RELEASE.

Ответы на вопрос(1)

Ваш ответ на вопрос