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

时间:2015-11-19 07:40:42

标签: asp.net asp.net-identity openid-connect aspnet-contrib

我正在使用下面的代码在OpenIdConnectServerProvider.AuthorizationProvider中创建一个ClaimIdentity。但是identity.Name不是searlized。如何让OpenIdConnectServer serarlize这个名字?感谢。

上一个问题是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));       

1 个答案:

答案 0 :(得分:8)

为避免泄露机密数据,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);

添加声明时,您还可以使用AddClaim参数destinations进行扩展:

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