【问题标题】:Redis caches the principal object issueRedis缓存主体对象问题
【发布时间】:2021-01-24 16:07:29
【问题描述】:

在使用 redis 时,由于 Principal 对象被缓存,我无法更改用户的属性。

我有一项用于更改用户属性的服务。为此,我创建了一个 CustomUserDetails 类并实现了 UserDetails 接口。 CustomUserDetails 类有 2 个字段; propertyid,currentPropertyid(瞬态)。查看实现:

public class CustomUserDetails implements UserDetails {
    private Long propertyid;
    private Long currentPropertyid;

    public Long getPropertyid() {
        if(getCurrentPropertyid() != null){
            return getCurrentPropertyid();
        }
        return propertyid;
    }
    
    public void setPropertyid(Long propertyid) {
        this.propertyid = propertyid;
    }

    @Transient
    public Long getCurrentPropertyid() {
        return currentPropertyid;
    }
    
    public void setCurrentPropertyid(Long propertyid) {
        this.currentPropertyid = propertyid;
    }
}

服务实现:

@PutMapping(value="change/property")
public void changeProperty(Long propertyid) {
    CustomUserDetails user = ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal())
    user.setCurrentPropertyid(propertyid);
}

因此,基本上服务的目的是更改 propertyid 以查看其他属性的数据。 这工作正常,但是当我启用 redis 时,它不起作用。一些 redis 如何缓存 Principal 对象。我没有在这里添加我的 redis 实现,因为在我的 redis 实现中,我没有任何缓存 UserDetails 对象的实现。无论如何,我已经注释掉了我在项目中实现的 RedisTemplates,但是 redis 没有被禁用,同样的问题。

有解决这个问题的办法吗?

【问题讨论】:

    标签: java spring spring-security redis


    【解决方案1】:

    我发现 redis 通过 OAuth2AccessToken 缓存主体对象。因此,我需要覆盖 OAuth2AccessToken。这是我更新的服务方法;

    @Autowired
    @Qualifier("customRedisTokenStore")
    CustomRedisTokenStore mCustomRedisTokenStore;
    
    @PutMapping(value="change/property")
    public void changeProperty(Long propertyid) {
        CustomUserDetails user = ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal())
        user.setCurrentPropertyid(propertyid);
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
            OAuth2AccessToken accessToken = mCustomRedisTokenStore.getAccessToken(oAuth2Authentication);
            mCustomRedisTokenStore.storeAccessToken(accessToken, oAuth2Authentication);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2013-09-02
      • 2016-03-29
      • 2017-06-08
      • 2014-10-05
      • 2012-07-16
      • 1970-01-01
      相关资源
      最近更新 更多