Select a theme

Spring Security - In-Memory Authentication using DaoAuthenticationProvider

Spring Security provides DaoAuthenticationProvider which requires a UserDetailsService and a passwordEncoder bean to perform username and password authentication.

Please note — we will use a spring boot project. You can access the maven dependencies here.


Create a Spring Configuration class and extend to WebSecurityConfigurerAdapter

Override the configure(AuthenticationManagerBuilder auth)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//we will set the newly created authentication provider here.
		// for example: auth.authenticationProvider(ourcustomAuthProviderInstance)


Add a password encoder bean

we are BCryptPasswordEncoder here.

  public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(4);


Create an instance of UserDetailsService

we will return an instance of InMemoryUserDetailsManager It is an implementation of UserDetailsService interface.

InMemoryUserDetailsManager provides constructors which can take either a collection or varargs array of UserDetails instance. That means, you are free to add multiple UserDetails instances .

public UserDetailsService inMemoryUserDetailsService() {
    UserDetails user1 = User.builder()
      .passwordEncoder((password) -> passwordEncoder().encode(password))
    return new InMemoryUserDetailsManager(user1);


Create a bean of DaoAuthenticationProvider

we will also set the instances

  public DaoAuthenticationProvider inMemoryDaoAuthenticationProvider() {
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    return daoAuthenticationProvider;

Finally add the DaoAuthenticationProvider in the configure method.

  protected void configure(AuthenticationManagerBuilder auth) throws Exception {

That is it. You can now run your Spring boot application and use the username and password of the user you just created for login.

You can access the source code from the GitHub repo here

If you have any feedback, let me know in the comments below and don't forget to give a thumbs up.