Identityserver4 添加了自定义声明,显示访问令牌中缺少的ID令牌

Identityserver4 添加了自定义声明,显示访问令牌中缺少的ID令牌,identityserver4,access-token,asp.net-core-identity,Identityserver4,Access Token,Asp.net Core Identity,我有一个.NET核心身份提供程序(也使用IdentityServer 4),它使用Azure AD对SPA应用程序进行身份验证。我正在使用从Azure接收的对象标识符值添加一个“oid”声明。问题是,从SPA应用程序中,我可以在ID令牌中看到“oid”声明,但在访问令牌中看不到它。我还需要访问令牌中的oid。以下是相关代码: Startup.cs services.AddAuthentication() .AddCookie("Cookies", options =&

我有一个.NET核心身份提供程序(也使用IdentityServer 4),它使用Azure AD对SPA应用程序进行身份验证。我正在使用从Azure接收的对象标识符值添加一个“oid”声明。问题是,从SPA应用程序中,我可以在ID令牌中看到“oid”声明,但在访问令牌中看不到它。我还需要访问令牌中的oid。以下是相关代码:

Startup.cs

services.AddAuthentication()
    .AddCookie("Cookies", options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(10);

    })
    .AddOpenIdConnect(ActiveDirectoryTenants.TenantA, ActiveDirectoryTenants.TenantA, options => Configuration.Bind("TenantAAzureAd", options))
    .AddOpenIdConnect(ActiveDirectoryTenants.TenantB, ActiveDirectoryTenants.TenantB, options => Configuration.Bind("TenantBAzureAd", options));
    
AddActiveDirectoryOpenIdConnectOptions(services, ActiveDirectoryTenants.TenantA);
AddActiveDirectoryOpenIdConnectOptions(services, ActiveDirectoryTenants.TenantB);
我有一个常见的功能,可以为这些配置添加其他选项。我试图在OnTokenValidated中添加oid声明,但在访问令牌中没有收到oid声明

protected virtual void AddActiveDirectoryOpenIdConnectOptions(IServiceCollection services, string tenant)
{
    services.Configure<OpenIdConnectOptions>(tenant, options =>
    {
        options.Authority = options.Authority + "/v2.0/"; 
        options.TokenValidationParameters.ValidateIssuer = false; 

        options.Events = new OpenIdConnectEvents
        {
            OnRedirectToIdentityProvider = ctx =>
            {
                ctx.ProtocolMessage.LoginHint = ctx.Properties.GetString("username");
                return Task.CompletedTask;
            },
            OnTokenValidated = ctx =>
            {
                //Maybe need to add oid here??? 
            }
        };
    });
}
SPA应用程序中接收的访问令牌(请注意缺少oid声明):


为了使声明在访问令牌中结束,您需要添加一个ApiScope并向其添加Userclaim名称。或者,添加包含UserClaim的ApiScope和ApiResource

var apiresource1=new ApiResource()
{
Name=“apiresource1”,//这是API的名称
ApiSecrets=新列表
{
新秘密(“myapisecret.Sha256())
},
Description=“这是订单Api资源描述”,
启用=真,
DisplayName=“订单API服务”,
Scopes=新列表{“apiscope1”},
UserClaims=新列表
{
//请求访问此API时应提供的自定义用户声明。
//这些声明将添加到访问令牌,而不是ID令牌!
“apiresource1-userclaim3”,
}
};

有关更多详细信息,请参见我的答案

谢谢您的回答!这使我朝着正确的方向前进。在将声明添加到从IResourceStore(从IdentityServer4)继承的实现类中的ApiResource之后,我现在可以看到自定义声明:)太好了!很高兴你成功了!
public async Task<IActionResult> ExternalLoginCallback(string returnUrl, string remoteError = null, string openIdScheme = null)
{
    var authResult = await HttpContext.AuthenticateAsync(openIdScheme ?? ActiveDirectoryTenants.TenantA);
    var externalUser = authResult.Principal;
    var claims = externalUser.Claims.ToList();
    var applicationUser = //gets the user based on the email found in claims, omitted for brevity
    
    await userManager.AddClaimAsync(applicationUser, new Claim("oid", claims.First(x => x.Type == http://schemas.microsoft.com/identity/claims/objectidentifier).Value));
    
    await signInManager.SignInAsync(applicationUser, false, "AzureAD");

    return Redirect("~/");
}
{
  "nbf": xxx,
  "exp": xxx,
  "iss": "https://localhost:3000", 
  "aud": "xxx-spa-test",
  "iat": xxx,
  "at_hash": "",
  "s_hash": "",
  "sid": "",
  "sub": "guid",
  "auth_time": 1620026953,
  "idp": "AzureAD",
  "display_name": "Test User",
  "oid": "guid",
  "role": [
    "Staff",
  ],
  "name": "test@azureaddomain",
  "amr": [
    "external"
  ]
}
{
  "nbf": xxx,
  "exp": xxx,
  "iss": "https://localhost:3000",
  "aud": [
    "https://localhost:3000/resources",
    "xxx-api-test-scope"
  ],
  "client_id": "xxx-spa-test",
  "sub": "guid",
  "auth_time": 1620026953,
  "idp": "AzureAD",
  "role": [
    "Staff",
  ],
  "name": "test@azureaddomain",
  "scope": [
    "openid",
    "profile",
    "xxx-api-test-scope"
  ],
  "amr": [
    "external"
  ]
}
var apiresource1 = new ApiResource()
{
    Name = "apiresource1",   //This is the name of the API
    ApiSecrets = new List<Secret>
    {
        new Secret("myapisecret".Sha256())
    },
    Description = "This is the order Api-resource description",
    Enabled = true,
    DisplayName = "Orders API Service",
    Scopes = new List<string> { "apiscope1"},
    UserClaims = new List<string>
    {
        //Custom user claims that should be provided when requesting access to this API.
        //These claims will be added to the access token, not the ID-token!
        "apiresource1-userclaim3",
    }
};