I use java configuration to configure Spring Security, and I have customized AuthenticationProvider and customized UserDetailsService, to add extra login field following http://forum.spring.io/forum/spring-projects/security/95715-extra-login-fields
I have difficulty to add both of the customized Classes into Spring Security framework by using java configuration. As java doc of AuthenticationProvider#authenticationProvider describes:
Add authentication based upon the custom AuthenticationProvider that is passed in. Since the AuthenticationProvider implementation is unknown, all customizations must be done externally and the AuthenticationManagerBuilder is returned immediately.
This method does NOT ensure that the UserDetailsService is available for the getDefaultUserDetailsService() method.
So my question is what is the approach to set UserDetailsService in this case?
The Authentication Manager is only a interface and actual implementation of the authenticate method is provided by the ProviderManager. The ProviderManager has a list of AuthenticationProviders. From it's authenticate method it calls the authenticate method of the appropriate AuthenticateProvider.
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which can be overridden to customize the process of finding the user. It is used by the DaoAuthenticationProvider to load details about the user during authentication.
The Authentication Provider Spring Security provides a variety of options for performing authentication. These options follow a simple contract; an Authentication request is processed by an AuthenticationProvider, and a fully authenticated object with full credentials is returned.
Step 1: Add the security jar or dependency in your application. Step 2: Create a security config class and extend the WebSecurityConfigurerAdapter class. Step 3: Add the annotation @EnableWebSecurity on top of the class. Step 4: For authentication, override the method configure(AuthenticationManagerBuilder auth) .
Here is an example of customized AuthenticationProvider and customized UserDetailsService:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider());
}
@Bean
AuthenticationProvider customAuthenticationProvider() {
CustomAuthenticationProvider impl = new CustomAuthenticationProvider();
impl.setUserDetailsService(customUserDetailsService());
/* other properties etc */
return impl ;
}
@Bean
UserDetailsService customUserDetailsService() {
/* custom UserDetailsService code here */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With