1234567891011121314151617181920212223242526272829303132333435363738 |
- [[servlet-authentication-cached]]
- = CachingUserDetailsService
- Spring Security's `CachingUserDetailsService` implements xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[UserDetailsService] offering support for caching authentication.
- `CachingUserDetailsService` provides caching support for `UserDetails` by delegating the authentication process to the provided `UserDetailsService`. The result is then stored in a `UserCache` to reduce computation in subsequent calls.
- Utilize this class by defining a `@Bean` of it that encapsulates a concrete implementation of `UserDetailsService` and set a `UserCache` to cache authenticated `UserDetails`.
- For example:
- [source,java]
- ----
- @Bean
- public CachingUserDetailsService cachingUserDetailsService(UserDetailsService delegate, UserCache userCache) {
- CachingUserDetailsService service = new CachingUserDetailsService(delegate);
- service.setUserCache(userCache);
- return service;
- }
- ----
- However, a preferable approach would be to use `@Cacheable` in your `UserDetailsService.loadUserByUsername(String)` implementation to cache `UserDetails` by `username`, reducing boilerplate and setup, especially if you are already using cache in your application.
- For example:
- [source,java]
- ----
- @Service
- public class MyCustomUserDetailsImplementation implements UserDetailsService {
- @Override
- @Cacheable
- public UserDetails loadUserByUsername(String username) {
- // some logic here to get the actual user details
- return userDetails;
- }
- }
- ----
|