
1. Overview
In this tutorial, we will learn how to configure and use UserDetailsService in Spring Security with examples.
We introduce two ways to configure UserDetailsService the first approach is by creating a bean of type UserDetailsService and the second way is by overriding the Spring security configure method.
We introduce two ways to configure UserDetailsService the first approach is by creating a bean of type UserDetailsService and the second way is by overriding the Spring security configure method.
2. Configure UserDetailsService
2.1 Declaring beans
In this section, we will create a UserDetailsService bean to do that we will create a configuration class and create an annotated method with the bean annotation that returns a UserDetailsService instance.
This code shows the implementation for the UserDetailsService using InMemoryUserDetailsManager()
This code shows the implementation for the UserDetailsService using InMemoryUserDetailsManager()
@Bean
public UserDetailsService userDetailsService(){
var UserDetailsService = new InMemoryUserDetailsManager();
var user = User.withUsername("admin").password("admin").authorities("read").build();
UserDetailsService.createUser(user);
return UserDetailsService;
}
For the implementation to work, we need to create a password encoder bean.
@Bean
public UserDetailsService userDetailsService(){
var UserDetailsService = new InMemoryUserDetailsManager();
var user = User.withUsername("admin").password("admin").authorities("read").build();
UserDetailsService.createUser(user);
return UserDetailsService;
}
2.1 Overriding configure method
The second way to configure UserDetailsService is to override the WebSecurityConfigurerAdapter configure method.
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
var userDetailsService = new InMemoryUserDetailsManager();
var user = User.withUsername("admin").password("admin").authorities("read").build();
userDetailsService.createUser(user);
auth.userDetailsService(userDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
3. Conclusion
In this tutorial, we learned the different methods to config UserDetailsService in Spring boot using in-memory credentials in the next tutorial we will learn how to use UserDetailsService with data sources like MySQL, PostgreSQL ...
0 Comments