从安全上下文中获取当前经过身份验证的用户作为spring缓存的密钥

ou6hu8tu  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(397)

我有一个没有参数的方法,我想缓存返回值。作为缓存密钥,我想从安全上下文中使用当前经过身份验证的用户

  1. @Cacheable(value = "resultCache", key="#userPrincipal.id")
  2. public result getResult() {}

是可能的还是我的想法错了。

bksxznpy

bksxznpy1#

您有四个选项来实现这一点:
发送 Authentication 对象作为方法参数:

  1. @Cacheable(value = "resultCache", key="#authentication.name")
  2. public Result getResult(Authentication authentication) {}

创建自定义 KeyGenerator 在你的生活中使用它 @Cacheable 注解

  1. public class CustomKeyGenerator implements KeyGenerator {
  2. @Override
  3. public Object generate(Object target, Method method, Object... params) {
  4. return SecurityContextHolder.getContext().getAuthentication().getName();
  5. }
  6. }
  7. @Configuration
  8. @EnableCaching
  9. public class CacheConfiguration {
  10. @Bean("customKeyGenerator")
  11. public KeyGenerator customKeyGenerator() {
  12. return new CustomKeyGenerator();
  13. }
  14. }
  15. @Cacheable(value = "resultCache", keyGenerator="customKeyGenerator")
  16. public Result getResult() {}

创建一个bean,为您提供密钥并通过 key 财产。我建议您采用这种方法,因为它允许您稍后更轻松地更改值。

  1. @Component
  2. public class CacheKeyProvider {
  3. public String getUsernameKey() {
  4. return SecurityContextHolder.getContext().getAuthentication().getName();
  5. }
  6. }
  7. @Cacheable(value = "resultCache", key="@cacheKeyProvider.getUsernameKey()")
  8. public Result getResult() {}

使用类型spel表达式

  1. @Cacheable(value = "resultCache", key="T(org.springframework.security.core.context.SecurityContextHolder.getContext()?.authentication?.name)")
  2. public Result getResult() {}

注意,我使用了 name 来自 Principal 在例子中。但是如果你有一个习惯 Principal 对象,您可以强制转换它并返回所需的任何属性。

展开查看全部

相关问题