【问题标题】:Sub claim missing from ProfileDataRequestContext.RequestedClaimTypesProfileDataRequestContext.RequestedClaimTypes 中缺少子声明
【发布时间】:2021-10-27 17:12:01
【问题描述】:

在 IdentityServer4 中,我定义了一个带有一些声明的 IdentityResource:

new IdentityResource {
  Name = "userdata",
  UserClaims = new List<string> {
    JwtClaimTypes.Subject,
    JwtClaimTypes.Role,
    JwtClaimTypes.Email,
    JwtClaimTypes.Name
  }
}

然后将其添加到客户端配置中的作用域中:

AllowedScopes = {
  IdentityServerConstants.StandardScopes.OpenId,
  "api1",
  "userdata"
}

在客户端应用程序中,我请求了该范围:

.AddOpenIdConnect("oidc", options => {
  options.Scope.Add("openid");
  options.Scope.Add("userdata");
  options.Scope.Add("offline_access");
  options.Scope.Add("api1");
}

在 IS4 中,我实现了 IProfileService 以向 id_token 添加一些声明。

public async Task GetProfileDataAsync(ProfileDataRequestContext context) {

  var sub = context.Subject.GetSubjectId();
  var user = await _userManager.FindByIdAsync(sub);
  if (user == null) {
    throw new ArgumentException("");
  }

  var principal = await _claimsFactory.CreateAsync(user);
  var userClaims = principal.Claims.ToList();

  var claims = new List<Claim> {
    userClaims.Find(x => x.Type == JwtClaimTypes.Subject),
    userClaims.Find(x => x.Type == JwtClaimTypes.Role),
    userClaims.Find(x => x.Type == JwtClaimTypes.Email),
    userClaims.Find(x => x.Type == JwtClaimTypes.Name),
    new Claim("iesseapetenantid", user.TenantId.ToString())
  };

  var requestedClaimTypes = context.RequestedClaimTypes;

  context.AddRequestedClaims(claims);
}

context.AddRequestedClaims(claims) 过滤传递的声明并仅添加客户端请求的声明。

问题在于 context.RequestedClaimTypes 中缺少 sub 声明,但其他三个声明存在:emailname角色

为什么缺少“sub”声明?

谢谢!

【问题讨论】:

  • 如果只想添加一些声明,则无需实现 IProfileService。看看答案here
  • @RuardvanElburg 在我的情况下,我需要实现IProfileService,因为我想动态注入一些声明。谢谢。

标签: asp.net-core identityserver4


【解决方案1】:

sub 声明是 spec 所需的声明,因此它是 StandardScopes.OpenId 的一部分。您无需另外设置或请求。

var sub = context.Subject.GetSubjectId();

假设sub 声明已经在上下文中。否则会抛出异常。

以上都是关于IdentityResourceid_token。可以在不引用用户的情况下为 ApiResource 创建 token

【讨论】:

  • 是的,我明白了,但问题仍然存在。即使我请求了 OpenId 范围,RequestedClaimTypes 也不包含子声明。所以它没有添加到 id_token 中。
  • hmm,这是两个不同的点:RequestedClaimTypes 不应包含sub,这仅适用于其他用户声明。但令牌必须包含sub
  • 对不起,我误说 sub 不在 id_token 中。正如您所说,重要的部分是RequestedClaimTypes 仅用于其他用户声明。这就是让我困惑的地方。谢谢。
【解决方案2】:

就我而言,问题出在声明映射配置中。

只需添加一行

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");

之前

services.AddAuthentication("Bearer")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 2013-07-11
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多