cached.adoc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. [[servlet-authentication-cached]]
  2. = CachingUserDetailsService
  3. Spring Security's `CachingUserDetailsService` implements xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[UserDetailsService] offering support for caching authentication.
  4. `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.
  5. Utilize this class by defining a `@Bean` of it that encapsulates a concrete implementation of `UserDetailsService` and set a `UserCache` to cache authenticated `UserDetails`.
  6. For example:
  7. [source,java]
  8. ----
  9. @Bean
  10. public CachingUserDetailsService cachingUserDetailsService(UserDetailsService delegate, UserCache userCache) {
  11. CachingUserDetailsService service = new CachingUserDetailsService(delegate);
  12. service.setUserCache(userCache);
  13. return service;
  14. }
  15. ----
  16. 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.
  17. For example:
  18. [source,java]
  19. ----
  20. @Service
  21. public class MyCustomUserDetailsImplementation implements UserDetailsService {
  22. @Override
  23. @Cacheable
  24. public UserDetails loadUserByUsername(String username) {
  25. // some logic here to get the actual user details
  26. return userDetails;
  27. }
  28. }
  29. ----