Может ли Spring иметь несколько ConfigurerAdapter?

Мне нужно добавить безопасность OAuth2 с помощью аутентификации ldap. Сначала я реализовал аутентификацию ldap и добавил экземпляр WebSecurityConfigurerAdapter.

@Configuration
@EnableWebSecurity
@Order(2)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin();
    }

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

    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication()
                .contextSource().url("ldaps://master:636/dc=domain,dc=com")
                .managerDn("cn=readonly,dc=domain,dc=com").managerPassword("123456")
                .and()
                .userSearchFilter("(uid={0})");
    }
}

Мне нужно добавить адаптер сервера ресурсов OAuth2 ResourceServerConfigurerAdapter

@Configuration
@Import({ DatabaseConfig.class })
@EnableResourceServer
@Order(1)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired DatabaseConfig databaseConfig;

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests()
                .anyRequest().authenticated();
    }


    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // converter.setSigningKey("123");
        final Resource resource = new ClassPathResource("public.txt");
        String publicKey = null;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);
        return converter;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }


    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(databaseConfig.dataSource());
    }

Похоже, что WebSecurityConfigurerAdapter и ResourceServerConfigurerAdapter конфликтуют, когда оба настроены.

Я играю с обоими методами configure(), но я могу получить доступ только через ldap, используя http://localhost:8080/login в моем Rest API, и не могу использовать мой угловой клиент, используя oauth http://localhost:8081/login

У меня возникает следующая ошибка при попытке доступа к ресурсу:

Failed to find refresh token for token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJqb2huIiwic2NvcGUiOlsiZm9vIiwicmVhZCIsIndyaXRlIl0sIm9yZ2FuaXphdGlvbiI6ImpvaG5vRnZiIiwiYXRpIjoiNDcyZTJiNDYtZjgxZS00NGJiLWEwNDMtMGYwZmRjMDMzY2U1IiwiZXhwIjoxNDc2NTQ5NjYzLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiN2UwNzRkZDktOWI0ZC00MTU0LWJjMzktMDlkY2U4Y2UyZTg2IiwiY2xpZW50X2lkIjoiZm9vQ2xpZW50SWRQYXNzd29yZCJ9.fuarTPL1O00Yg6b3BPibwux1ZtlmrHaPCJkgjsJni_51B3NEHkdB9kqbABK3IkMWMlZdqY8xfR-zMpY9SxFkpRFDfyvosgLcsTZ...
Handling error: InvalidGrantException, Invalid refresh token: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVC...

person Dimitri Kopriwa    schedule 20.09.2016    source источник


Ответы (2)


У меня такая же проблема. Может быть, мое решение не изящно, но оно работает для меня.

Я пробовал OAuth2ResourceServerConfig, который расширяет WebSecurityConfig и реализует ResourceServerConfigurer.

Ваш OAuth2ResourceServerConfig должен быть таким

@Configuration
@Import({ DatabaseConfig.class })
@EnableResourceServer
@Order(1)
public class OAuth2ResourceServerConfig extends WebSecurityConfig implements ResourceServerConfigurer {

    @Autowired DatabaseConfig databaseConfig;

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests()
                .anyRequest().authenticated();
    }


    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // converter.setSigningKey("123");
        final Resource resource = new ClassPathResource("public.txt");
        String publicKey = null;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);
        return converter;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }


    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(databaseConfig.dataSource());
    }
person Bukharov Sergey    schedule 09.03.2017

Согласно этот пост, я думаю, вы можете использовать предыдущую версию, добавив это в свою конфигурацию (yml или свойства):

security:
  oauth2:
    resource:
        filter-order: 3

И я попытался добавить аннотацию @Order в конфигурацию моего исходного сервера, как и вы, и получил ту же проблему. Итак, я думаю, что аннотация @Order не влияет на ResourceServerConfigurerAdapter, но отлично работает с WebSecurityConfig. Я не знаю, это ошибка или задумано.

person Xin    schedule 01.12.2017