java - Redis缓存主体对象问题

标签 java spring spring-security redis

在使用 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/

相关文章:

java - 使用 Spring 上下文配置文件的 Jersey 2.4 测试 - DI 不工作

spring-security - Spring Security 3.0 - Intercept-URL - 所有页面都需要身份验证,但一个

javascript - 如何实现节点模拟退火(TSP)

java - 一个非常简单的 java 程序出现问题,无法显示正确的结果

java - 如何从命令行在 JUnit 4 中运行也被忽略的测试?

java - Spring Integration DSL SFTP 良好实践

java - Spring MVC 不记录所有异常

spring-security - 升级到 springBootVersion = '1.3.3.RELEASE' 后使用 RestTemplate 出现异常

java - 使用 Spring Security 3 散列和加盐密码

java - 只接受部分类的通用方法