为已经通过身份验证的用户添加/删除 auth cookie 中的声明

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

我有一个多租户系统(每个客户端的数据库),其中一个用户可以访问多个客户端。用户通过身份验证后,会生成一个 cookie 用于身份验证(我使用 ASP.NET Core Identity 和 Cookie auth 进行身份验证)。

由于该用户可以访问来自多个客户端(不同数据库)的数据,因此在进行身份验证后,我检查哪些客户端可以用户访问并提供视图以选择一个客户端继续。

此时我想将 TenantId 存储到 cookie 中作为声明,因为我不想在每次请求时将相同的信息从客户端传递到服务器。所以我创建了一个看起来像这样的 HttpPost API 端点:

[HttpPost]
public ActionResult<SetClientResponse> SetClient(SetClientRequest request)
{
    // To do:
    // Here I thought to store a SetClientRequest.TenantId property as claim in a identity cookie
}

我试过这样的事情:

var principal = _httpContextAccessor.HttpContext?.User;
var identity = new System.Security.Claims.ClaimsIdentity();

identity.AddClaim(new Claim("TenantId", request.TenantId));
principal.AddIdentity(identity);

这行得通,我可以在 principal.Claims 中看到这个声明,但它不会永久存储(在下一次请求时,这个声明就消失了)。

如何让这个声明永久保存在cookie中?或者也许有更好的方法来实现这一目标?我不想在 url 中显示 TenantId(和其他一些信息),我想尽可能地保护恶意用户的数据。

asp.net-core cookies asp.net-core-webapi asp.net-core-identity
© www.soinside.com 2019 - 2024. All rights reserved.