Конфигурация многосерверных аннотаций Spring OAuth2 (ресурс и авторизация)

Я использую следующее:

  • весна 4.2
  • весенняя безопасность 4.0.2
  • весна oauth2 2.0.7

Я пытаюсь настроить один сервер, который обрабатывает:

  • общие материалы MVC (некоторые защищены, а некоторые нет)
  • сервер авторизации
  • ресурсный сервер

Похоже, что конфигурация сервера ресурсов не ограничивается / rest / **, но переопределяет ВСЮ конфигурацию безопасности. то есть вызовы защищенных ресурсов NON-OAuth не защищены (т.е. фильтр не улавливает их и не перенаправляет для входа в систему).

Конфигурация (я удалил некоторые вещи для простоты):

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter  {



        @Autowired
        private TokenStore tokenStore;

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources
                .resourceId(RESOURCE_ID)
                .tokenStore(tokenStore)
                .stateless(true);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .requestMatchers()
                    .antMatchers("/rest/**")
                    .and()
                .authorizeRequests()
                    .antMatchers("/rest/**").access("hasRole('USER') and #oauth2.hasScope('read')");

        }

    }

@Configuration
@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

    }
   @Bean
    protected AuthenticationEntryPoint authenticationEntryPoint() {
        OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
        entryPoint.setRealmName("example");
        return entryPoint;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth
            .authenticationProvider(mongoClientAuthenticationProvider)
            .authenticationProvider(mongoUserAuthenticationProvider)
            .userDetailsService(formUserDetailsService);
    }

    @Bean
    protected ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception{
        ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.afterPropertiesSet();
        return filter;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
        .requestMatchers()
            .antMatchers("/account/**", "/account")
            .antMatchers("/oauth/token")
            .antMatchers("/login")
            .and()
        .authorizeRequests()
            .antMatchers("/account/**", "/account").hasRole("USER")
            .antMatchers("/oauth/token").access("isFullyAuthenticated()")
            .antMatchers("/login").permitAll()
            .and()
        .exceptionHandling()
            .accessDeniedPage("/login?authentication_error=true")
            .and()
        .csrf()
            .disable()
        .logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .and()
        .formLogin()
            .loginProcessingUrl("/login")
            .failureUrl("/login?authentication_error=true")
            .loginPage("/login")
        ;

        http.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class);

    }

person checklist    schedule 25.08.2015    source источник


Ответы (2)


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

@Configuration
@EnableWebSecurity
@Order(4)
public class SecurityConfig  extends WebSecurityConfigurerAdapter{}

Аннотация @EnableResourceServer создает WebSecurityConfigurerAdapter с жестко заданным порядком (из 3). Изменить порядок прямо сейчас невозможно из-за технических ограничений в Spring, поэтому вам следует избегать использования order = 3 в других WebSecurityConfigurerAdapters в вашем приложении (Spring Security сообщит вам, если вы забудете).

Ссылка:

http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#multiple-httpsecurity.

http://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/config/annotation/web/configuration/EnableResourceServer.html

person KSTN    schedule 29.08.2015
comment
Я уже пробовал с заказом, но это не сработало. Обратите внимание, что класс ресурса (EnableResourceServer) не расширяет WebSecurityConfigurerAdapter. Кроме того, как бы вы решили, что будет первым? Мне нужно, чтобы они оба совпали. - person checklist; 29.08.2015
comment
@EnableResourceServer автоматически создаст WebSecurityConfigurerAdapter с порядком = 3. - person KSTN; 29.08.2015

Решение состоит в том, что вы должны использовать следующую версию lib (s), иначе вы столкнетесь с этой проблемой. Надеюсь на эту помощь. Вы не можете использовать версию spring -security 4.0.2. spring-security-acl-3.2.7.RELEASE.jar spring-security-config-3.2.7.RELEASE.jar spring-security-core-3.2.7.RELEASE.jar spring-security-oauth2-2.0.7.RELEASE .jar весна-безопасность-taglibs-3.2.7.RELEASE.jar

person Kyaw Khaing    schedule 08.09.2015
comment
Не могли бы вы объяснить причину и основу ответа? - person checklist; 08.09.2015