【问题标题】:Spring Security Authentication Server with multiple authentication providers for client_credentialsSpring Security Authentication Server 具有多个用于 client_credentials 的身份验证提供程序
【发布时间】:2019-05-15 04:03:09
【问题描述】:

我正在尝试使用 Spring Security 身份验证设置身份验证服务器,并且需要为 client_credentials 提供多个身份验证提供程序。

我已经进行了大量搜索,但尚未找到如何配置 Spring Security 以将我的自定义身份验证提供程序添加到客户端凭据身份验证提供程序列表中。我发现的每种方法都会导致相同的 2 个提供程序用于客户端凭据身份验证。匿名和 dao 身份验证提供程序。

如果在弄清楚如何为多个客户端凭据身份验证提供程序配置 spring 安全身份验证服务器方面提供任何帮助,我将不胜感激。

授权服务器配置

@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 的身份验证时,我没有看到自定义的添加到提供程序列表中,只有匿名和 dao 身份验证提供程序。

【问题讨论】:

  • 你能分享你的代码吗?
  • 我用一些代码和我尝试过的一种方法更新了这个问题。

标签: spring-boot spring-security


【解决方案1】:

我终于能够将 Spring Security 身份验证服务器的配置设置为可以为 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 中,我们现在可以将我们的提供者添加到提供者管理器列表中。

我不确定这是完全正确的方法,但它似乎可以让我们做我们想做的事。

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 2012-03-07
    • 2018-05-07
    • 2016-05-23
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    相关资源
    最近更新 更多