Quick revision
The short answer
We implement loadUserByUsername() to fetch the user and its roles in one query, throw UsernameNotFoundException when the user is absent, and return a UserDetails with the username, the encoded password, the authorities and the status flags (locked, disabled, expired). DaoAuthenticationProvider calls the service, checks the account status, then compares the presented password with the stored hash through the PasswordEncoder. By default it hides UsernameNotFoundException as BadCredentialsException, and it runs the encoder against a dummy password when the user does not exist, so neither the message nor the timing reveals which usernames exist.
What to remember
In this answer, we wrote a UserDetailsService that loads the user and its roles in one fetch-join query, throws UsernameNotFoundException when the user is missing, and returns a User with the password hash, ROLE_ authorities and status flags. DaoAuthenticationProvider calls it, checks lock, enable and expiry status, compares the password through the PasswordEncoder, checks credential expiry and builds the authenticated token. It hides missing users as BadCredentialsException and hashes a dummy password for them, so neither the message nor the timing reveals which usernames exist.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We implement loadUserByUsername() to fetch the user and its roles in one query, throw UsernameNotFoundException when the user is absent, and return a UserDetails with the username, the encoded password, the authorities and the status flags (locked, disabled, expired). DaoAuthenticationProvider calls the service, checks the account status, then compares the presented password with the stored hash through the PasswordEncoder. By default it hides UsernameNotFoundException as BadCredentialsException, and it runs the encoder against a dummy password when the user does not exist, so neither the message nor the timing reveals which usernames exist.
Why this question is asked
Loading users from our own database is the most common real-world authentication setup, and the code looks trivial: one method, one repository call. The interesting parts are what happens around it. Lazy role collections that blow up outside a transaction, locked accounts that still log in, and responses that tell an attacker which usernames are valid. Interviewers ask this to see both the code and an understanding of what the framework does with it. In this answer, we will recap the UserDetails contract, map the entity, write the service, follow DaoAuthenticationProvider step by step, and look at the protections against user enumeration.
1A Quick Recap of UserDetails
Spring Security does not know our user table. It asks a UserDetailsService, an interface with one method, loadUserByUsername(String), to return a UserDetails: a small read-only view of the user with exactly what authentication needs. That is the username, the password hash, the granted authorities (roles and permissions), and four status flags: isAccountNonLocked(), isEnabled(), isAccountNonExpired() and isCredentialsNonExpired().
Keeping this separate from our JPA entity is deliberate. The UserDetails object may end up stored in the HTTP session and serialised, so it should be a simple object, not a managed entity with lazy collections and a link to the persistence context.
2Mapping the User and Roles
A typical model has a user table and a role table joined many-to-many. JPA makes collections lazy by default for many-to-many, which is usually right elsewhere in the application, so we keep it lazy and fetch the roles explicitly when we load a user for login.
Notice the fetch join. Spring Security calls our service from a filter, before any controller and outside any transaction, and Open Session in View, if enabled, does not cover security filters. If we loaded the user and then touched a lazy roles collection, we would get a LazyInitializationException, or, with some configurations, one extra query per user. Fetching the roles in the same query avoids both.
3Writing the Service
The service maps the entity to Spring Security's User class, a ready-made UserDetails implementation with a builder.
Notice the ROLE_ prefix. hasRole("ADMIN") checks for the authority ROLE_ADMIN, so we either store role names without the prefix and add it here, as above, or store full authority names and use hasAuthority(). The @Transactional annotation is a second safety net: if someone later removes the fetch join, the lazy collection still loads inside the method rather than failing.
4What DaoAuthenticationProvider Does With the Result
When a login arrives, for example from form login or HTTP Basic, the AuthenticationManager hands the UsernamePasswordAuthenticationToken to DaoAuthenticationProvider, the provider for username and password. It runs a fixed sequence of steps.
- Call loadUserByUsername()User and authorities from our service
- User found?YesContinueNoHash a dummy password, throw BadCredentialsException
- Locked, disabled or expired?YesThrow LockedException or similarNoContinue
- PasswordEncoder.matches()?YesContinueNoThrow BadCredentialsException
- Credentials expired?YesThrow CredentialsExpiredExceptionNoBuild authenticated token
5 steps in order. Play them, or step through them one at a time.
Status checks run before the password comparison.
First it calls our loadUserByUsername(). Then it runs the pre-authentication checks on the status flags: a locked account throws LockedException, a disabled one DisabledException, an expired one AccountExpiredException. Next it asks the PasswordEncoder whether the presented password matches the stored hash; a mismatch throws BadCredentialsException. Then the post-authentication check rejects expired credentials with CredentialsExpiredException. If the encoder reports that the stored hash uses an outdated algorithm or strength and a UserDetailsPasswordService is configured, the provider re-hashes the password and stores the upgrade. Finally it builds an authenticated token with the user's authorities, and the manager erases the password from it.
Notice the order: status checks run before the password check. A locked account is rejected even with the right password, which is what we want, but it also means a LockedException can be returned for a wrong password. So the response the user sees should be the same generic message for all of these failures, with the specific reason logged on the server.
5Hiding Which Usernames Exist
An attacker who can tell 'no such user' from 'wrong password' can collect a list of valid usernames and then try passwords only against those. DaoAuthenticationProvider defends against this in two ways.
First, hideUserNotFoundExceptions is true by default, so UsernameNotFoundException is converted into BadCredentialsException with the same message as a wrong password. Second, timing. Checking a bcrypt hash takes roughly 100 milliseconds, while a missing user would otherwise return almost instantly, and that difference is easy to measure. So when the user does not exist, the provider still runs the password encoder against a dummy hash it prepared at startup, making both paths take about the same time.
Our own code must not undo this. A custom failure handler that writes e.getMessage() or the exception class name into the response, or a registration page that says 'username already taken', can reveal the same information through another door.
6Follow-up questions
Should our JPA entity implement UserDetails directly?
It is possible but usually a bad idea. The entity then ends up in the security context and the session, with its lazy collections and persistence state, and every change to the entity affects security. Mapping to a small UserDetails object keeps authentication independent and serialisable.
How does Spring Boot pick up this service?
If our UserDetailsService and a PasswordEncoder are beans, and we have not defined our own AuthenticationProvider or AuthenticationManager, Spring Security configures a DaoAuthenticationProvider with them automatically, and Boot stops creating its default in-memory user.
Which PasswordEncoder should we use?
PasswordEncoderFactories.createDelegatingPasswordEncoder() is the usual choice. It stores hashes with an id prefix such as {bcrypt}, uses bcrypt for new passwords, and can still verify older formats, which, together with UserDetailsPasswordService, lets us upgrade hashes gradually as users log in.
7Conclusion
In this answer, we wrote a UserDetailsService that loads the user and its roles in one fetch-join query, throws UsernameNotFoundException when the user is missing, and returns a User with the password hash, ROLE_ authorities and status flags. DaoAuthenticationProvider calls it, checks lock, enable and expiry status, compares the password through the PasswordEncoder, checks credential expiry and builds the authenticated token. It hides missing users as BadCredentialsException and hashes a dummy password for them, so neither the message nor the timing reveals which usernames exist.
Open with
I'd implement loadUserByUsername with a repository method that fetches the user and its roles in one query, using a left join fetch, because Spring Security calls the service from a filter, outside any transaction and outside Open Session in View, so a lazy roles collection would throw LazyInitializationException.
Then, if they want more
I'd also mark the method read-only transactional as a safety net. If the user isn't there, I throw UsernameNotFoundException. Otherwise I map the entity to Spring Security's User builder: username, the stored password hash, authorities with the ROLE_ prefix so hasRole works, and the flags: accountLocked, disabled, accountExpired.
I keep the entity separate from UserDetails, since the details may be stored in the session. DaoAuthenticationProvider then does the work. It calls my service, runs pre-authentication checks, so a locked, disabled or expired account throws the matching exception, then compares the presented password with the hash through the PasswordEncoder and throws BadCredentialsException on mismatch, then checks for expired credentials.
If the encoder says the hash is outdated and a UserDetailsPasswordService exists, it upgrades it. Then it returns an authenticated token and the manager erases the credentials.
Two protections matter: by default it converts UsernameNotFoundException into BadCredentialsException, so the message doesn't reveal whether a username exists, and when the user is missing it still checks the password against a dummy hash so the response time is the same. I'd make sure my own failure handler doesn't leak the reason either.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Security reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement a UserDetailsService that loads users from a JPA repository, including locked...": https://scrivio-interview-library.netlify.app/spring-boot/authentication/77749267a9/