Custom UserDetailsService in Spring Security
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()andisAccountNonLocked()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
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 {
}
package com.javabytechie.gym;
import java.time.LocalDate;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class MemberPrincipal implements UserDetails {
private final Member member;
public MemberPrincipal(Member member) {
this.member = member;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return member.roles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).toList();
}
@Override
public String getPassword() {
return member.passwordHash();
}
@Override
public String getUsername() {
return member.email();
}
@Override
public boolean isAccountNonExpired() {
return !member.membershipEnds().isBefore(LocalDate.now());
}
@Override
public boolean isAccountNonLocked() {
return !member.locked();
}
// Extra data for controllers and services
public String homeBranch() {
return member.homeBranch();
}
}
package com.javabytechie.gym;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MemberUserDetailsService implements UserDetailsService {
private final MemberDirectory directory;
public MemberUserDetailsService(MemberDirectory directory) {
this.directory = directory;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return directory.findByEmail(email)
.map(MemberPrincipal::new)
.orElseThrow(() -> new UsernameNotFoundException("No member with this email"));
}
}
package com.javabytechie.gym;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
// Stands in for a database table of members
@Repository
public class MemberDirectory {
private final List<Member> members;
public MemberDirectory(PasswordEncoder encoder) {
LocalDate today = LocalDate.now();
this.members = List.of(
new Member("meera@fithub.example", encoder.encode("meera-pass"), "Jayanagar",
today.plusMonths(4), false, Set.of("MEMBER")),
new Member("dev@fithub.example", encoder.encode("dev-pass"), "Hebbal",
today.minusMonths(2), false, Set.of("MEMBER")), // membership ended
new Member("sam@fithub.example", encoder.encode("sam-pass"), "Jayanagar",
today.plusMonths(9), true, Set.of("MEMBER"))); // locked by staff
}
public Optional<Member> findByEmail(String email) {
String wanted = email.trim().toLowerCase(Locale.ROOT);
return members.stream().filter(m -> m.email().equals(wanted)).findFirst();
}
}
package com.javabytechie.gym;
import java.util.List;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClassController {
@GetMapping("/api/classes")
public List<String> classesAtMyBranch(@AuthenticationPrincipal MemberPrincipal member) {
return List.of(member.homeBranch() + ": Yoga 07:00", member.homeBranch() + ": Spin 18:30");
}
}
package com.javabytechie.gym;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().hasRole("MEMBER"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
package com.javabytechie.gym;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GymApplication {
public static void main(String[] args) {
SpringApplication.run(GymApplication.class, args);
}
}
5. Step-by-Step Code Explanation
Memberstays framework-free. The domain record does not implement any Spring Security interface. It implementsSerializablebecause the principal that wraps it may be stored in an HTTP session.MemberPrincipaladapts the member. It answersgetUsername()with the email andgetPassword()with the stored hash, and turns each role into aROLE_authority.- Domain rules become status checks. An ended membership makes
isAccountNonExpired()false, and the staff lock makesisAccountNonLocked()false.isEnabled()andisCredentialsNonExpired()are not overridden, so their defaults (true) apply. - The service normalises the email.
findByEmailtrims and lower-cases the input, soMEERA@FitHub.examplefinds the same member. Unknown emails throwUsernameNotFoundException. - No extra wiring. Because
MemberUserDetailsServiceis the onlyUserDetailsServicebean, Spring Security uses it automatically with thePasswordEncoderbean. - The controller reads the principal.
@AuthenticationPrincipal MemberPrincipalinjects the object your service created during login, sohomeBranch()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:
$ 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:
AccountExpiredException: User account has expired
LockedException: User account is locked
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Fits any storage and any login identifier | You own the mapping code and its tests |
| Domain rules enforced by Spring Security's standard checks | Status is evaluated only at login; an already logged-in session is not re-checked |
Rich principal available everywhere through @AuthenticationPrincipal | A large principal stored in sessions costs memory and must be serializable |
| Keeps the domain model independent of Spring Security | Two 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 likeMemberPrincipal. - Forgetting the
ROLE_prefix.hasRole("MEMBER")looks forROLE_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,
loadUserByUsernameruns on every request. Cache carefully or move browser users to session or token login.
9. Summary
- A custom
UserDetailsServiceloads users from your own storage by any login identifier, such as email. - A custom
UserDetailswraps your domain object and maps your account rules to the four status methods. DaoAuthenticationProviderenforces those rules and reports specific exceptions in the log, while the client sees a generic 401.- A single
UserDetailsServicebean is picked up automatically. @AuthenticationPrincipalgives controllers your custom principal and its extra fields.
10. References
Frequently Asked Questions (FAQ)
Q1. How do I log in with an email address instead of a username?
Treat the email as the username. In loadUserByUsername, look the user up by email (normalised to lower case), and return it from getUsername() in your UserDetails.
Q2. Should my JPA entity implement UserDetails?
It can, but a separate wrapper class is cleaner. It keeps Spring Security types out of the domain model and lets you choose exactly which fields the principal exposes.
Q3. How do I get the custom UserDetails object in a controller?
Add a parameter annotated with @AuthenticationPrincipal and typed as your principal class, for example @AuthenticationPrincipal MemberPrincipal member.
Q4. Which exceptions do the UserDetails status methods cause?
isEnabled() false causes DisabledException, isAccountNonLocked() false causes LockedException, isAccountNonExpired() false causes AccountExpiredException and isCredentialsNonExpired() false causes CredentialsExpiredException.
Q5. Do I need to register the custom UserDetailsService with Spring Security?
Not if it is the only UserDetailsService bean. Spring Security detects it and creates a DaoAuthenticationProvider that uses it together with your PasswordEncoder bean.