Spring OAuth2 конфигурация на анотации за множество сървъри (ресурс и оторизация)

Използвам следното:

  • пролет 4.2
  • пружинна сигурност 4.0.2
  • spring 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). Не е възможно да промените реда в момента поради технически ограничения през пролетта, така че трябва да избягвате използването на 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 spring-security-taglibs-3.2.7.RELEASE.jar

person Kyaw Khaing    schedule 08.09.2015
comment
Можете ли да обясните причината и основанието за отговора? - person checklist; 08.09.2015