An AuthenticationProvider is the class that actually decides whether a login request is valid. A custom provider replaces the default check with your own rules, such as branch, status or lockout limits. Spring Security passes the login request to it, and it returns an authenticated user or throws an exception. It is used when username and password alone are not enough to allow a login.
Features
- Full control over the login rules
- Extra login data (here, the branch code) used in the decision
- Different rules for different branches (active branch, own-branch login, lockout limit)
- Clear failure messages through exceptions (
BadCredentialsException,LockedException,DisabledException) - Roles assigned after a successful login
- Session-based login through a REST endpoint
- Works with
ProviderManager, which can hold more than one provider
Custom Authentication Provider Types
- DaoAuthenticationProvider (default): It loads the user through
UserDetailsServiceand compares the password. It is enough when only username and password matter. - Custom AuthenticationProvider (used here): You implement
authenticate()andsupports()and write your own rules, here the branch rules for the employee login. - Multiple Providers in a ProviderManager: Providers are tried one by one, so for example one provider can handle employees and another can handle contractors.
- Specialised Providers: Ready-made providers for LDAP, JWT or OAuth2 logins, or your own provider for those. They are not built in this example.
Hands-on Experiment: Building a Multi-Branch Employee Login System with a Custom Authentication Provider
Aim: To build a Spring Boot application that authenticates employees with a custom provider that applies branch-specific login rules.
Software/Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
- Project: Maven | Language: Java | Spring Boot: 3.3.x
- Group:
com.example| Artifact:branch-login| Packaging: Jar | Java: 17 - Dependencies: Spring Web, Spring Security, Spring Data JPA, MySQL Driver
Step 2: Project Structure
branch-login
├── pom.xml
└── src/main
├── java/com/example/branchlogin
│ ├── BranchLoginApplication.java
│ ├── entity/Branch.java
│ ├── entity/Employee.java
│ ├── repository/BranchRepository.java
│ ├── repository/EmployeeRepository.java
│ ├── service/EmployeeService.java
│ ├── service/BranchAuthenticationProvider.java
│ ├── service/SecurityConfig.java
│ ├── controller/AuthController.java
│ └── controller/EmployeeController.java
└── resources/application.properties
Step 3: Create the files according to the project structure
package com.example.branchlogin.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "branch")
public class Branch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String branchCode;
@Column(nullable = false)
private String branchName;
// Rule 1: employees can log in only to an active branch
private boolean active = true;
// Rule 2: each branch decides how many wrong passwords lock an account
private int maxFailedAttempts = 3;
public Branch() {
}
public Branch(String branchCode, String branchName, boolean active, int maxFailedAttempts) {
this.branchCode = branchCode;
this.branchName = branchName;
this.active = active;
this.maxFailedAttempts = maxFailedAttempts;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getBranchCode() { return branchCode; }
public void setBranchCode(String branchCode) { this.branchCode = branchCode; }
public String getBranchName() { return branchName; }
public void setBranchName(String branchName) { this.branchName = branchName; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
public int getMaxFailedAttempts() { return maxFailedAttempts; }
public void setMaxFailedAttempts(int maxFailedAttempts) { this.maxFailedAttempts = maxFailedAttempts; }
}
package com.example.branchlogin.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fullName;
@Column(nullable = false, unique = true)
private String username;
// never returned in responses
@Column(nullable = false)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
// EMPLOYEE or MANAGER
@Column(nullable = false)
private String role;
// the branch this employee belongs to
@Column(nullable = false)
private String branchCode;
private int failedAttempts = 0;
private boolean locked = false;
public Employee() {
}
public Employee(String fullName, String username, String password, String role, String branchCode) {
this.fullName = fullName;
this.username = username;
this.password = password;
this.role = role;
this.branchCode = branchCode;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
public String getBranchCode() { return branchCode; }
public void setBranchCode(String branchCode) { this.branchCode = branchCode; }
public int getFailedAttempts() { return failedAttempts; }
public void setFailedAttempts(int failedAttempts) { this.failedAttempts = failedAttempts; }
public boolean isLocked() { return locked; }
public void setLocked(boolean locked) { this.locked = locked; }
}
package com.example.branchlogin.repository;
import com.example.branchlogin.entity.Branch;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface BranchRepository extends JpaRepository<Branch, Long> {
Optional<Branch> findByBranchCode(String branchCode);
boolean existsByBranchCode(String branchCode);
}
package com.example.branchlogin.repository;
import com.example.branchlogin.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Optional<Employee> findByUsername(String username);
boolean existsByUsername(String username);
List<Employee> findByBranchCode(String branchCode);
}
package com.example.branchlogin.service;
import com.example.branchlogin.entity.Branch;
import com.example.branchlogin.entity.Employee;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Custom provider: username + password + branch code.
* The branch code arrives in authentication.getDetails().
*/
@Component
public class BranchAuthenticationProvider implements AuthenticationProvider {
private final EmployeeService employeeService;
private final PasswordEncoder passwordEncoder;
public BranchAuthenticationProvider(EmployeeService employeeService, PasswordEncoder passwordEncoder) {
this.employeeService = employeeService;
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String rawPassword = String.valueOf(authentication.getCredentials());
String branchCode = authentication.getDetails() == null ? "" : authentication.getDetails().toString();
Employee employee = employeeService.findEmployee(username)
.orElseThrow(() -> new BadCredentialsException("Invalid username or password"));
// Rule 1: a locked account cannot log in
if (employee.isLocked()) {
throw new LockedException("Account is locked. Ask your branch manager to unlock it");
}
// Rule 2: password check, wrong attempts are counted per branch limit
if (!passwordEncoder.matches(rawPassword, employee.getPassword())) {
employeeService.recordFailedAttempt(username);
throw new BadCredentialsException("Invalid username or password");
}
// Rule 3: the branch must exist and be active
Branch branch = employeeService.findBranch(branchCode)
.orElseThrow(() -> new BadCredentialsException("Unknown branch: " + branchCode));
if (!branch.isActive()) {
throw new DisabledException("Branch is inactive: " + branchCode);
}
// Rule 4: the employee can log in only to his own branch
if (!employee.getBranchCode().equals(branch.getBranchCode())) {
throw new BadCredentialsException("Employee does not belong to branch " + branchCode);
}
employeeService.resetFailedAttempts(username);
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
username, null, List.of(new SimpleGrantedAuthority("ROLE_" + employee.getRole())));
result.setDetails(branchCode);
return result;
}
// This provider handles username/password tokens
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
package com.example.branchlogin.service;
import com.example.branchlogin.entity.Branch;
import com.example.branchlogin.entity.Employee;
import com.example.branchlogin.repository.BranchRepository;
import com.example.branchlogin.repository.EmployeeRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeService {
private final EmployeeRepository employeeRepository;
private final BranchRepository branchRepository;
private final PasswordEncoder passwordEncoder;
public EmployeeService(EmployeeRepository employeeRepository,
BranchRepository branchRepository,
PasswordEncoder passwordEncoder) {
this.employeeRepository = employeeRepository;
this.branchRepository = branchRepository;
this.passwordEncoder = passwordEncoder;
}
public Optional<Employee> findEmployee(String username) {
return employeeRepository.findByUsername(username);
}
public Optional<Branch> findBranch(String branchCode) {
return branchRepository.findByBranchCode(branchCode);
}
public List<Branch> findAllBranches() {
return branchRepository.findAll();
}
public List<Employee> findByBranch(String branchCode) {
return employeeRepository.findByBranchCode(branchCode);
}
// Counts a wrong password and locks the account when the
// employee's own branch limit is reached
@Transactional
public void recordFailedAttempt(String username) {
employeeRepository.findByUsername(username).ifPresent(employee -> {
int max = branchRepository.findByBranchCode(employee.getBranchCode())
.map(Branch::getMaxFailedAttempts)
.orElse(3);
employee.setFailedAttempts(employee.getFailedAttempts() + 1);
if (employee.getFailedAttempts() >= max) {
employee.setLocked(true);
}
employeeRepository.save(employee);
});
}
@Transactional
public void resetFailedAttempts(String username) {
employeeRepository.findByUsername(username).ifPresent(employee -> {
if (employee.getFailedAttempts() > 0) {
employee.setFailedAttempts(0);
employeeRepository.save(employee);
}
});
}
// A manager can unlock only employees of his own branch
@Transactional
public Employee unlock(String managerUsername, String targetUsername) {
Employee manager = employeeRepository.findByUsername(managerUsername)
.orElseThrow(() -> new IllegalArgumentException("Manager not found"));
Employee target = employeeRepository.findByUsername(targetUsername)
.orElseThrow(() -> new IllegalArgumentException("Employee not found: " + targetUsername));
if (!manager.getBranchCode().equals(target.getBranchCode())) {
throw new IllegalArgumentException("You can unlock only employees of your own branch");
}
target.setLocked(false);
target.setFailedAttempts(0);
return employeeRepository.save(target);
}
public void createDefaultData() {
seedBranch("HYD", "Hyderabad", true, 5);
seedBranch("BLR", "Bangalore", true, 3);
seedBranch("CHN", "Chennai", false, 3); // inactive branch
seedEmployee("Hyd Employee", "emp101", "emp123", "EMPLOYEE", "HYD");
seedEmployee("Hyd Manager", "mgr101", "mgr123", "MANAGER", "HYD");
seedEmployee("Blr Employee", "emp201", "emp456", "EMPLOYEE", "BLR");
seedEmployee("Blr Manager", "mgr201", "mgr456", "MANAGER", "BLR");
seedEmployee("Chn Employee", "emp301", "emp789", "EMPLOYEE", "CHN");
}
private void seedBranch(String code, String name, boolean active, int maxFailedAttempts) {
if (!branchRepository.existsByBranchCode(code)) {
branchRepository.save(new Branch(code, name, active, maxFailedAttempts));
}
}
private void seedEmployee(String fullName, String username, String password, String role, String branchCode) {
if (!employeeRepository.existsByUsername(username)) {
employeeRepository.save(new Employee(fullName, username, passwordEncoder.encode(password), role, branchCode));
}
}
}
package com.example.branchlogin.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// The manager that calls our custom provider
@Bean
public AuthenticationManager authenticationManager(BranchAuthenticationProvider provider) {
return new ProviderManager(provider);
}
// Used to keep the logged-in user in the HTTP session
@Bean
public SecurityContextRepository securityContextRepository() {
return new HttpSessionSecurityContextRepository();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http,
SecurityContextRepository securityContextRepository) throws Exception {
http
.csrf(csrf -> csrf.disable()) // REST API tested with Postman
.securityContext(sc -> sc.securityContextRepository(securityContextRepository))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/login").permitAll()
.requestMatchers("/api/branches", "/api/employees/branch", "/api/employees/*/unlock").hasRole("MANAGER")
.anyRequest().authenticated())
.exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.logout(logout -> logout
.logoutUrl("/api/logout")
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID"));
return http.build();
}
}
package com.example.branchlogin.controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class AuthController {
private final AuthenticationManager authenticationManager;
private final SecurityContextRepository securityContextRepository;
public AuthController(AuthenticationManager authenticationManager,
SecurityContextRepository securityContextRepository) {
this.authenticationManager = authenticationManager;
this.securityContextRepository = securityContextRepository;
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody Map<String, String> body,
HttpServletRequest request,
HttpServletResponse response) {
String username = body.get("username");
String password = body.get("password");
String branchCode = body.get("branchCode");
if (username == null || password == null || branchCode == null) {
return ResponseEntity.badRequest()
.body(Map.of("error", "username, password and branchCode are required"));
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(branchCode); // branch travels to the custom provider
try {
Authentication authentication = authenticationManager.authenticate(token);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
securityContextRepository.saveContext(context, request, response); // creates the session
return ResponseEntity.ok(Map.of(
"message", "Login successful",
"username", authentication.getName(),
"branch", branchCode,
"roles", authentication.getAuthorities().toString()));
} catch (AuthenticationException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("error", ex.getMessage()));
}
}
}
package com.example.branchlogin.controller;
import com.example.branchlogin.entity.Branch;
import com.example.branchlogin.entity.Employee;
import com.example.branchlogin.service.EmployeeService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class EmployeeController {
private final EmployeeService service;
public EmployeeController(EmployeeService service) {
this.service = service;
}
// any logged-in employee
@GetMapping("/employees/me")
public Employee me(Authentication authentication) {
return service.findEmployee(authentication.getName())
.orElseThrow(() -> new IllegalArgumentException("Employee not found"));
}
// MANAGER only: employees of the manager's own branch
@GetMapping("/employees/branch")
public List<Employee> branchEmployees(Authentication authentication) {
Employee manager = service.findEmployee(authentication.getName())
.orElseThrow(() -> new IllegalArgumentException("Manager not found"));
return service.findByBranch(manager.getBranchCode());
}
// MANAGER only: unlock a locked employee of the same branch
@PostMapping("/employees/{username}/unlock")
public Employee unlock(@PathVariable String username, Authentication authentication) {
return service.unlock(authentication.getName(), username);
}
// MANAGER only
@GetMapping("/branches")
public List<Branch> branches() {
return service.findAllBranches();
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> badRequest(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
package com.example.branchlogin;
import com.example.branchlogin.service.EmployeeService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class BranchLoginApplication {
public static void main(String[] args) {
SpringApplication.run(BranchLoginApplication.class, args);
}
// Creates demo branches and employees on first start
@Bean
CommandLineRunner seedData(EmployeeService service) {
return args -> service.createDefaultData();
}
}
spring.application.name=branch-login
server.port=8080
# MySQL (database is created automatically if missing)
spring.datasource.url=jdbc:mysql://localhost:3306/branch_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=trueCode language: PHP (php)
Step 4: Run the BranchLoginApplication

