跳到主要内容

缓存 UserDetails

QWen Max 中英对照 Caching UserDetails Caching UserDetails

Spring Security 提供了使用 CachingUserDetailsService 来缓存 UserDetails 的支持。或者,你可以使用 Spring Framework 的 @Cacheable 注解。无论哪种情况,你都需要禁用凭证擦除,以便验证从缓存中检索到的密码。

CachingUserDetailsService

Spring Security 的 CachingUserDetailsService 实现了 UserDetailsService 以提供对缓存 UserDetails 的支持。CachingUserDetailsService 通过委托给提供的 UserDetailsService 来为 UserDetails 提供缓存支持。然后将结果存储在 UserCache 中,以减少后续调用中的计算量。

以下示例简单地定义了一个 @Bean,它封装了 UserDetailsService 的具体实现和用于缓存 UserDetailsUserCache

@Bean
public CachingUserDetailsService cachingUserDetailsService(UserCache userCache) {
UserDetailsService delegate = ...;
CachingUserDetailsService service = new CachingUserDetailsService(delegate);
service.setUserCache(userCache);
return service;
}
java

@Cacheable

另一种方法是在你的 UserDetailsService 实现中使用 Spring Framework 的 @Cacheable 来按 username 缓存 UserDetails。这种方法的好处是配置更简单,特别是如果你已经在应用程序的其他地方使用了缓存。

以下示例假设已经配置了缓存,并使用 @Cacheable 注解 loadUserByUsername

@Service
public class MyCustomUserDetailsImplementation implements UserDetailsService {

@Override
@Cacheable
public UserDetails loadUserByUsername(String username) {
// some logic here to get the actual user details
return userDetails;
}
}
java

禁用凭证擦除

无论你使用 CachingUserDetailsService 还是 @Cacheable,都需要禁用 凭证擦除,以便 UserDetails 在从缓存中检索时包含一个用于验证的 password。以下示例通过配置 Spring Security 提供的 AuthenticationManagerBuilder 来禁用全局 AuthenticationManager 的凭证擦除:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// ...
return http.build();
}

@Bean
public UserDetailsService userDetailsService() {
// Return a UserDetailsService that caches users
// ...
}

@Autowired
public void configure(AuthenticationManagerBuilder builder) {
builder.eraseCredentials(false);
}

}
java