快取 UserDetails

Spring Security 提供使用 CachingUserDetailsService 快取 UserDetails 的支援。或者,您可以使用 Spring Framework 的 @Cacheable 註解。在任一種情況下,您都需要停用憑證清除,以便驗證從快取中檢索的密碼。

CachingUserDetailsService

Spring Security 的 CachingUserDetailsService 實作 UserDetailsService,以提供快取 UserDetails 的支援。CachingUserDetailsService 透過委派給提供的 UserDetailsService 來提供 UserDetails 的快取支援。然後,結果會儲存在 UserCache 中,以減少後續呼叫的計算。

以下範例僅定義一個 @Bean,其封裝了 UserDetailsServiceUserCache 的具體實作,用於快取 UserDetails

提供 CachingUserDetailsService @Bean
  • Java

  • Kotlin

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

@Cacheable

另一種方法是在您的 UserDetailsService 實作中使用 Spring Framework 的 @Cacheable,以依 username 快取 UserDetails。此方法的優點是組態更簡單,特別是當您已在應用程式的其他地方使用快取時。

以下範例假設已設定快取,並使用 @Cacheable 註解 loadUserByUsername

使用 @Cacheable 註解的 UserDetailsService
  • Java

  • Kotlin

@Service
public class MyCustomUserDetailsImplementation implements UserDetailsService {

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

    @Cacheable
    override fun loadUserByUsername(username: String): UserDetails {
        // some logic here to get the actual user details
        return userDetails
    }
}

停用憑證清除

無論您使用 CachingUserDetailsService@Cacheable,您都需要停用 憑證清除,以便 UserDetails 將包含一個 password,以便在從快取中檢索時進行驗證。以下範例透過組態 Spring Security 提供的 AuthenticationManagerBuilder,為全域 AuthenticationManager 停用憑證清除

為全域 AuthenticationManager 停用憑證清除
  • Java

  • Kotlin

@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);
	}

}
import org.springframework.security.config.annotation.web.invoke

@Configuration
@EnableWebSecurity
class SecurityConfig {

	@Bean
	fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
		// ...
		return http.build()
	}

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

	@Autowired
	fun configure(builder: AuthenticationManagerBuilder) {
		builder.eraseCredentials(false)
	}

}