Spring Security,更新SecurityContextHolder

问题描述 投票:0回答:1

我有多租户环境,一个数据库,每个租户都有单独的架构。

在用户登录时,我加载默认租户,一切都很好。我创建方法switchTenant应该切换当前租户(默认一个)与选定的一个。我有部分工作的解决方案,我在HttpSession中保存了这些信息。一切正常,有一些副作用,如:在tomcat上重启用户需要重新启动,或者android应用程序关闭时用户会丢失会话。

试图通过在SecurityContext中存储当前租户信息来寻找更好的解决方案来替换HttpSession。当然我失败了,这就是为什么我要求你帮忙。

这是我正在努力工作的相关代码:

TenantInterceptor(这里一切都很好)

...
@Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        String schema = SecurityUtils.getCurrentSchema().orElse("");
        if (schema.equals("")) {
            TenantContext.setCurrentTenant("public");
        } else {
            TenantContext.setCurrentTenant(schema);
        }
        return true;
    }
...

SecurityUtils帮助类(这里一切都很好)

...
public static Optional<String> getCurrentSchema() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication()).map(authentication -> {
            if (authentication.getPrincipal() instanceof TenantUser) {
                TenantUser springSecurityUser = (TenantUser) authentication.getPrincipal();
                return springSecurityUser.getCurrentSchema();
            }
            return null;
        });
    }
...

服务类(我需要修复)

...
public void switchTenant(Tenant tenant) {
        Optional<TenantDTO> tenantExist = this.findAllUserTenants().stream()
            .filter(t -> t.getName().equals(tenant.getName())).findFirst();
        if (tenantExist.isPresent()) {

            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Authentication newAuth = null;
            if (auth.getClass() == UsernamePasswordAuthenticationToken.class) {
                TenantUser principal = (TenantUser) auth.getPrincipal();
                principal.setCurrentSchema(tenant.getSchema());
                newAuth = new UsernamePasswordAuthenticationToken(principal, auth.getCredentials(), auth.getAuthorities());
            }
            SecurityContextHolder.getContext().setAuthentication(newAuth);
...

TenantUser类

public class TenantUser extends org.springframework.security.core.userdetails.User {

    private String userId;

    private String currentSchema;

    public TenantUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }
...

无论如何,这行代码:SecurityContextHolder.getContext()。setAuthentication(newAuth);总是让我的旧身份验证不是具有更新的当前租户架构的身份验证

感谢帮助。

spring spring-security multi-tenant
1个回答
0
投票

方法很糟糕。因为我使用jwt令牌进行身份验证,所以最好的方法是将当前租户架构存储到令牌中。在租户交换机上,我使用新的当前架构刷新令牌并将其发送回客户端。

© www.soinside.com 2019 - 2024. All rights reserved.