0
0
SpringbootHow-ToBeginner · 4 min read

How to Configure Authentication Manager in Spring Boot

In Spring Boot, configure the AuthenticationManager by exposing it as a bean in a @Configuration class using AuthenticationManagerBuilder or by defining a SecurityFilterChain bean with custom authentication providers. This setup allows Spring Security to handle user authentication with your custom logic or user details service.
📐

Syntax

To configure the AuthenticationManager in Spring Boot, you typically create a @Bean method inside a @Configuration class. You use AuthenticationManagerBuilder to set up user details or authentication providers, then expose the AuthenticationManager as a bean.

Alternatively, with Spring Security 5.7+, you configure a SecurityFilterChain bean and inject the AuthenticationManager where needed.

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
            .build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .formLogin();
        return http.build();
    }
}
💻

Example

This example shows how to configure an AuthenticationManager with an in-memory user for authentication in Spring Boot. It demonstrates defining users and passwords, exposing the manager as a bean, and securing all HTTP requests.

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
            .inMemoryAuthentication()
            .withUser("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .and()
            .and()
            .build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .formLogin();
        return http.build();
    }
}
Output
When running the Spring Boot application, all HTTP requests require authentication. Accessing any URL redirects to a login form where you can log in with username 'user' and password 'password'.
⚠️

Common Pitfalls

  • Not exposing AuthenticationManager as a bean: Without a bean, Spring Security cannot use your custom authentication setup.
  • Using deprecated WebSecurityConfigurerAdapter: Since Spring Security 5.7, this class is deprecated; use SecurityFilterChain and bean methods instead.
  • Forgetting password encoding: Passwords must be encoded with a PasswordEncoder, or authentication will fail.
  • Misconfiguring HttpSecurity: Not calling http.build() or missing authorization rules can cause security misbehavior.
java
/* Wrong way: Using deprecated WebSecurityConfigurerAdapter */
//@Configuration
//public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//            .withUser("user")
//            .password("password") // No encoding - will fail
//            .roles("USER");
//    }
//}

/* Right way: Use beans and password encoder */
@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
            .inMemoryAuthentication()
            .withUser("user")
            .password(passwordEncoder.encode("password"))
            .roles("USER")
            .and()
            .and()
            .build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .formLogin();
        return http.build();
    }
}
📊

Quick Reference

AuthenticationManager Configuration Cheat Sheet:

  • Define AuthenticationManager as a @Bean in a @Configuration class.
  • Use AuthenticationManagerBuilder to set up users or authentication providers.
  • Always use a PasswordEncoder to encode passwords.
  • Configure SecurityFilterChain bean to define HTTP security rules.
  • Avoid deprecated WebSecurityConfigurerAdapter class.

Key Takeaways

Expose AuthenticationManager as a @Bean to customize authentication in Spring Boot.
Use AuthenticationManagerBuilder with a PasswordEncoder to define users or providers.
Configure SecurityFilterChain bean for HTTP security and authentication flow.
Avoid deprecated WebSecurityConfigurerAdapter; prefer modern bean-based configuration.
Always encode passwords to prevent authentication failures.