Custom Authentication Provider and UserDetailsService in Spring Security

πŸš€ Why Customize Authentication?

Spring Security provides powerful default authentication mechanisms. But real-world applications often need custom logic β€” such as validating users from a database, LDAP, or a third-party service. That’s where a Custom Authentication Provider and UserDetailsService shine.

With this setup, you gain full control over how credentials are verified and user data is retrieved.

Custom Authentication Provider and UserDetailsService

πŸ“¦ Maven Dependencies

Add the following to your pom.xml:

🧩 Project Structure

com.kscodes.springboot.security.customauth
β”œβ”€β”€ config/
β”‚ └── SecurityConfig.java
β”œβ”€β”€ controller/
β”‚ └── AuthController.java
β”œβ”€β”€ model/
β”‚ └── AppUser.java
β”œβ”€β”€ security/
β”‚ β”œβ”€β”€ CustomAuthenticationProvider.java
β”‚ └── CustomUserDetailsService.java
└── CustomAuthApplication.java

πŸ”§ Step 1: Create a User Entity

AppUser.java

You can later connect this to a database.

πŸ” Step 2: Implement UserDetailsService

CustomUserDetailsService.java

πŸ›‘οΈ Step 3: Create a Custom Authentication Provider

CustomAuthenticationProvider.java

πŸ” Step 4: Configure Spring Security

SecurityConfig.java

🌐 Step 5: Authentication Controller

AuthController.java

πŸ” Test It Out

Run the application and test login:

  • Visit: http://localhost:8080/home
  • Browser will prompt for login
  • Enter john / pass123

βœ… You’ll see the secured content if authentication succeeds using your Custom Authentication Provider and UserDetailsService.

⚠️ Best Practices

  • Use PasswordEncoder (e.g. BCryptPasswordEncoder) instead of plain password comparison.
  • Fetch users from a real database using repositories.
  • Add logging and throttling to prevent brute force attacks.

πŸ“š References