Я пытаюсь настроить сервер аутентификации с использованием аутентификации 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, я не увидел пользовательскую, добавленную в список провайдеров, только анонимная и дао-аутентификация.провайдеры.