Сервер аутентификации Spring Security с несколькими провайдерами аутентификации для client_credentials - PullRequest
0 голосов
/ 14 декабря 2018

Я пытаюсь настроить сервер аутентификации с использованием аутентификации Spring Security, и мне нужно иметь несколько провайдеров аутентификации для client_credentials.

Я провел немало поиска и пока не нашел, как настроить Spring Security длядобавить мой пользовательский поставщик проверки подлинности в список поставщиков проверки подлинности учетных данных клиента.Каждый подход, который я нашел, приводит к тому же 2 провайдерам для аутентификации учетных данных клиента.Анонимные и дао-провайдеры аутентификации.

Буду признателен за помощь в выяснении того, как настроить сервер аутентификации Spring Spring для нескольких провайдеров аутентификации учетных данных клиента.

AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter 
{
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()")
            .passwordEncoder(passwordEncoder())
            .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()

            .withClient("sampleClientId").authorizedGrantTypes("implicit")
            .scopes("read", "write", "foo", "bar")
            .autoApprove(false)
            .accessTokenValiditySeconds(3600)
            .redirectUris("http://localhost:8083/")

            .and()

            .withClient("fooClientIdPassword")
            .secret(passwordEncoder().encode("secret"))
            .authorizedGrantTypes("password", "authorization_code", "refresh_token")
            .scopes("foo", "read", "write")
            .accessTokenValiditySeconds(3600)       // 1 hour
            .refreshTokenValiditySeconds(2592000)   // 30 days
            .redirectUris("xxx")

            .and()

            .withClient("barClientIdPassword")
            .secret(passwordEncoder().encode("secret"))
            .authorizedGrantTypes("client_credentials", "refresh_token")
            .scopes("bar", "read", "write")
            .resourceIds("kip-apis")
            .accessTokenValiditySeconds(3600)       // 1 hour
            .refreshTokenValiditySeconds(2592000)   // 30 days

            .and()

            .withClient("testImplicitClientId")
            .autoApprove(true)
            .authorizedGrantTypes("implicit")
            .scopes("read", "write", "foo", "bar")
            .redirectUris("xxx");
    }

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain
            .setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));

        endpoints.authenticationManager(authenticationManager)
            .tokenServices(tokenServices())
            .tokenStore(tokenStore())
            .tokenEnhancer(tokenEnhancerChain);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
         JwtAccessTokenConverter converter = new JwtAccessTokenConverter();        
        converter.setSigningKey("123");                
        return converter;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

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

   @Bean
   public BCryptPasswordEncoder passwordEncoder() {
       return new BCryptPasswordEncoder();
   }
}

WebSecurityConfig:

@Configuration
@EnableWebSecurity( debug = true )  // turn off the default configuration 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin().disable() // disable form authentication
            .anonymous().disable() // disable anonymous user
            .authorizeRequests().anyRequest().denyAll(); // denying all access
    }

    @Autowired
    public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("john").password(passwordEncoder.encode("123")).roles("USER").and()
          .withUser("tom").password(passwordEncoder.encode("111")).roles("ADMIN").and()
          .withUser("user1").password(passwordEncoder.encode("pass")).roles("USER").and()
          .withUser("admin").password(passwordEncoder.encode("nimda")).roles("ADMIN");
    }

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

Я попробовал несколько вариантов, чтобы попытаться добавить дополнительный поставщик проверки подлинности для предоставления учетных данных клиента.Например, в WebSecurityConfig ...

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
{
    auth.authenticationProvider(customDaoAuthenticationProvider);
}

Это не сработало, и когда я проходил проверку подлинности для client_credentials, я не увидел пользовательскую, добавленную в список провайдеров, только анонимная и дао-аутентификация.провайдеры.

1 Ответ

0 голосов
/ 17 декабря 2018

Мне удалось наконец получить конфигурацию сервера проверки подлинности Spring в точке, где мы можем добавить несколько провайдеров для client_credentials.

@Configuration
@EnableAuthorizationServer
public class AuthenticationServerConfig  extends AuthorizationServerConfigurerAdapter {     
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.addTokenEndpointAuthenticationFilter(clientCredentialsTokenEndpointFilter());
    }

    @Bean
    protected ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() {
        ClientCredentialsTokenEndpointFilter cctef = new CustomClientCredentialsTokenEndpointFilter();       
        cctef.setAuthenticationManager(clientAuthenticationManager());
        return cctef;
    }

    @Bean
    protected ProviderManager clientAuthenticationManager() {
        return new ProviderManager(Arrays.asList(authProvider()));
    }

    @Bean
    protected DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider authProvider = new CustomDaoAuthenticationProvider();
        authProvider.setUserDetailsService(clientDetailsUserService());
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }    

    @Bean
    protected BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    protected UserDetailsService clientDetailsUserService() {
        return new ClientDetailsUserDetailsService(clientDetailsService());
    }

    @Bean
    protected ClientDetailsService clientDetailsService() {     
        return new ClientDetailsService() {
            @Override
            public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
                BaseClientDetails details = new BaseClientDetails();
                details.setClientId("barClientIdPassword");
                details.setClientSecret(passwordEncoder().encode("secret"));
                details.setAuthorizedGrantTypes(Arrays.asList("client_credentials"));
                details.setScope(Arrays.asList("read", "trust"));
                details.setResourceIds(Arrays.asList("kip-apis"));
                Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
                authorities.add(new SimpleGrantedAuthority("ROLE_CLIENT"));
                details.setAuthorities(authorities);
                details.setAccessTokenValiditySeconds(3600);    //1hr
                details.setRegisteredRedirectUri(null);
                return details;
            }
        };
    }

    @Bean
    public AuthenticationEntryPoint oauthAuthenticationEntryPoint() {
        OAuth2AuthenticationEntryPoint aep = new OAuth2AuthenticationEntryPoint();
        aep.setRealmName("theRealm");
        return aep;     
    }
    @Bean
    public AuthenticationEntryPoint clientAuthenticationEntryPoint() {
        OAuth2AuthenticationEntryPoint aep = new OAuth2AuthenticationEntryPoint();
        aep.setRealmName("theRealm/client");
        return aep;     
    }

    @Bean
    public AccessDeniedHandler oauthAccessDeniedHandler() {
        return new OAuth2AccessDeniedHandler();
    }    
}

В clientAuthenticationManager теперь мы можем добавить наших провайдеров в провайдерсписок менеджера.

Я не уверен, что это абсолютно правильный способ заставить это работать, но, похоже, он позволяет нам делать то, что мы хотели.

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