00:00

Custom UserDetailsService in Spring Security

Last updated:

A custom UserDetailsService connects Spring Security to the way your application already stores users. The built-in managers expect fixed tables and a plain username, but real systems log people in by email, keep memberships that expire, lock accounts for their own reasons and attach extra data such as a home branch or a tenant ID.

This tutorial builds a custom UserDetailsService and a custom UserDetails for a gym chain. Members sign in with their email address, expired memberships and locked accounts are rejected through Spring Security's own status checks, and controllers read the member's home branch straight from the logged-in principal.

1. What Is a Custom UserDetailsService?

It is your own class that implements UserDetailsService and its single method, loadUserByUsername. Inside, you query your own storage and convert the result into a UserDetails object. The UserDetailsService tutorial explains the interface and the built-in implementations; this page is about writing one yourself.

Most custom implementations also come with a custom UserDetails class. It wraps your domain object, answers Spring Security's questions (password hash, authorities, account status) and exposes extra fields that the rest of your code needs.

2. Why Write Your Own?

  • Your login name is not a username. Many applications use an email address or a phone number, often compared without case sensitivity.
  • Your account rules are domain rules. A gym membership has an end date, a subscription can lapse, an admin can suspend a user. Mapping these to isAccountNonExpired() and isAccountNonLocked() lets Spring Security enforce them during login.
  • You need more than a name after login. A custom principal carries IDs and attributes, so controllers do not have to reload the user on every request.
  • Your users live somewhere else. A legacy table, a JPA entity or a remote user service can all sit behind the same interface. For a JPA-specific version, see Spring Security with Spring Data JPA.

3. How the Pieces Fit Together

Custom UserDetailsService and principalDaoAuthenticationProvider calls MemberUserDetailsService, which loads a Member from MemberDirectory and wraps it in MemberPrincipal. After login the principal is available to controllers through @AuthenticationPrincipal. DaoAuthentication Provider MemberUserDetails Service (yours) MemberDirectory findByEmail(...) MemberPrincipal implements UserDetails Controller @AuthenticationPrincipal
Figure 1: your service turns a domain object into a principal; the same principal reaches your controller after login.

The provider never sees your Member record. It only talks to the UserDetails interface, so you are free to model members however your domain requires.

4. A Complete Example: Gym Members Logging In by Email

Each member has an email address, a BCrypt password hash, a home branch, a membership end date and a locked flag. To keep the focus on Spring Security, MemberDirectory holds members in memory; in a real system it would query a database. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.gym;

import java.io.Serializable;
import java.time.LocalDate;
import java.util.Set;

// The gym's own idea of a member; it knows nothing about Spring Security
public record Member(String email, String passwordHash, String homeBranch,
                     LocalDate membershipEnds, boolean locked, Set<String> roles)
        implements Serializable {
}

5. Step-by-Step Code Explanation

  1. Member stays framework-free. The domain record does not implement any Spring Security interface. It implements Serializable because the principal that wraps it may be stored in an HTTP session.
  2. MemberPrincipal adapts the member. It answers getUsername() with the email and getPassword() with the stored hash, and turns each role into a ROLE_ authority.
  3. Domain rules become status checks. An ended membership makes isAccountNonExpired() false, and the staff lock makes isAccountNonLocked() false. isEnabled() and isCredentialsNonExpired() are not overridden, so their defaults (true) apply.
  4. The service normalises the email. findByEmail trims and lower-cases the input, so MEERA@FitHub.example finds the same member. Unknown emails throw UsernameNotFoundException.
  5. No extra wiring. Because MemberUserDetailsService is the only UserDetailsService bean, Spring Security uses it automatically with the PasswordEncoder bean.
  6. The controller reads the principal. @AuthenticationPrincipal MemberPrincipal injects the object your service created during login, so homeBranch() is available without another lookup.

6. Expected Output

Requests from an active member (with two spellings of the email), a member whose membership ended and a locked member:

Terminal
$ curl -u meera@fithub.example:meera-pass localhost:8080/api/classes
HTTP/1.1 200
["Jayanagar: Yoga 07:00","Jayanagar: Spin 18:30"]

$ curl -u MEERA@FitHub.example:meera-pass localhost:8080/api/classes
HTTP/1.1 200
["Jayanagar: Yoga 07:00","Jayanagar: Spin 18:30"]

$ curl -u dev@fithub.example:dev-pass localhost:8080/api/classes
HTTP/1.1 401
{"timestamp":"2026-11-18T12:14:12.467Z","status":401,"error":"Unauthorized","path":"/api/classes"}

$ curl -u sam@fithub.example:sam-pass localhost:8080/api/classes
HTTP/1.1 401
{"timestamp":"2026-11-18T12:14:12.536Z","status":401,"error":"Unauthorized","path":"/api/classes"}

Both spellings of Meera's email work, and the response uses her home branch from the principal. Dev and Sam both get a plain 401. The DEBUG log shows the different reasons, raised by DaoAuthenticationProvider from the status methods you implemented:

Terminal
AccountExpiredException: User account has expired
LockedException: User account is locked

7. Advantages and Limitations

AdvantagesLimitations
Fits any storage and any login identifierYou own the mapping code and its tests
Domain rules enforced by Spring Security's standard checksStatus is evaluated only at login; an already logged-in session is not re-checked
Rich principal available everywhere through @AuthenticationPrincipalA large principal stored in sessions costs memory and must be serializable
Keeps the domain model independent of Spring SecurityTwo classes (service and principal) instead of a ready-made manager

8. Common Mistakes and Best Practices

  • Making the entity implement UserDetails. It works, but it mixes security into your domain model and makes JPA entities harder to evolve. Prefer a small wrapper like MemberPrincipal.
  • Forgetting the ROLE_ prefix. hasRole("MEMBER") looks for ROLE_MEMBER. See role vs authority.
  • Case-sensitive email lookup. Normalise the login name both when storing and when searching.
  • Putting secrets or large objects in the principal. Keep only what requests need: IDs, names and authorities.
  • Doing expensive work per request. With HTTP Basic, loadUserByUsername runs on every request. Cache carefully or move browser users to session or token login.

9. Summary

  • A custom UserDetailsService loads users from your own storage by any login identifier, such as email.
  • A custom UserDetails wraps your domain object and maps your account rules to the four status methods.
  • DaoAuthenticationProvider enforces those rules and reports specific exceptions in the log, while the client sees a generic 401.
  • A single UserDetailsService bean is picked up automatically.
  • @AuthenticationPrincipal gives controllers your custom principal and its extra fields.

10. References