在不同软件中使用IdentityServer登录后设置声明

时间:2018-09-21 11:48:50

标签: asp.net asp.net-core identityserver4

我有两个软件,想集成到一个identityserver中。两者都是软件,使用共享数据库的多租户

所有表都有一个名为TenantId的列,在我的DbContext(EF核心)中,我过滤了Where(x => x.TenantId == TenantId)。目前,我将此TenantId存储在Claim中,并使用一种简单的解决方案来生成JWT

在google搜索中,我已经看到在access_token中添加声明的一种方法是通过ProfileService,但是我的问题是,在每种软件中,用户可能具有不同的TenantId

this问题中,他们使用OnTokenValidated添加新的版权声明

但是我想知道,谁返回该软件的acess_token? API或IdentityServer,因为在这种情况下,您需要成为API才能添加新的Claims

摘要:我只希望identityserver登录并生成令牌,授权和其他逻辑将直接存在于每个软件中

1 个答案:

答案 0 :(得分:2)

在添加的链接中,您可以看到access_token实际上没有被修改。发生的是,access_token中的声明已映射到User.Identity。并在OnTokenValidated中向该User.Identity添加了其他声明。

问题在于tenantid不适合作为声明,因为IdentityClaims应该建模独立于上下文的Identity,而tenantid的某些东西是上下文依赖的。

对于资源,您不能使用OnTokenValidated。而是使用中间件。我建议您看一下IdentityServer团队的解决方案:PolicyServer

简而言之,在进行身份验证(IdentityServer)之后,策略服务器将根据配置的授权向User.Identity添加声明。

API(=资源)有两个部分:

  1. 使用授权声明扩展User.Identity
  2. 政策,因为应该在此进行逻辑。

然后您将拥有所需的内容。基于资源的授权。

PolicyServer使用json设置文件,但是您可以使用自己的商店对其进行扩展。该示例缺少常规声明,但是您可以使用声明扩展Policy模型:

// Just the lines to include claims.
public class Policy
{
    public List<Claim> Claims { get; internal set; } = new List<Claim>();

    internal Task<PolicyResult> EvaluateAsync(ClaimsPrincipal user)
    {
        var claims = Claims.Select(x => new Claim { Name = x.Name, Value = x.Value }).ToArray();

        var result = new PolicyResult()
        {
            Claims = claims
        };
    }
}

在配置中:

"Policy": {
  "claims": [
    {
      "name": "tenantid",
      "value": "44"
    }
  ],
  "roles": [

在中间件中,将声明添加到User.Identity中,例如:

id.AddClaims(claims);