在使用 redis 时,由于 Principal 对象被缓存,我无法更改用户的属性。
我有一项用于更改用户属性的服务。为此,我创建了一个 CustomUserDetails 类并实现了 UserDetails 接口(interface)。 CustomUserDetails 类有 2 个字段; propertyid,currentPropertyid( transient )。查看实现:
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 没有被禁用,同样的问题。
任何想法来处理这个问题?
最佳答案
我发现 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);
}
关于java - Redis缓存主体对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64282361/