如何指定现有 ClaimsIdentity 的目的地?

How to specify the destination for an existing ClaimsIdentity?

我正在使用以下代码在 OpenIdConnectServerProvider.AuthorizationProvider 中创建 ClaimIdentity。但是 identity.Name 没有被标记。如何让 OpenIdConnectServer 序列化名称?谢谢

上一题在这里How to create a ClaimIdentity in asp.net 5

var user = await userManager.FindByNameAsync(context.UserName);
var factory = context.HttpContext.RequestServices.GetRequiredService<IUserClaimsPrincipalFactory<ApplicationUser>>();
var identity = await factory.CreateAsync(user);                
context.Validated(new ClaimsPrincipal(identity));       

为避免泄露机密数据,AspNet.Security.OpenIdConnect.Server 拒绝序列化未明确指定目的地的声明。

要序列化名称(或任何其他声明),您可以使用 .SetDestinations 扩展名:

var principal = await factory.CreateAsync(user);

var name = principal.FindFirst(ClaimTypes.Name);
if (name != null) {
    // Use "id_token" to serialize the claim in the identity token or "access_token"
    // to serialize it in the access token. You can also specify both destinations.
    name.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                         OpenIdConnectConstants.Destinations.IdentityToken);
}

context.Validate(principal);

添加声明时,您还可以使用带有 destinations 参数的 AddClaim 扩展:

identity.AddClaim(ClaimTypes.Name, "Pinpoint",
     OpenIdConnectConstants.Destinations.AccessToken,
     OpenIdConnectConstants.Destinations.IdentityToken);