使用 IdentityServer3 获取声明

Getting Claims With IdentityServer3

我正在关注 Using OAuth to Secure Your ASP.NET API course on Pluralsight。我已经用一些 InMemoryUsers 设置了 IdentityServer,其中一个看起来像这样...

public static List<InMemoryUser> Get()
{
    return new List<InMemoryUser>
       {
           new InMemoryUser
           {
               Username = "user@domain.com",
               Password = "password",
               Subject = "user@domain.com",
               Claims = new[]
                        {
                            new Claim(Constants.ClaimTypes.Id, "96cddc1de66641829237b7f09869b1c8"),
                            new Claim(Constants.ClaimTypes.Name, "Some Full name example
                        }
           },
       };
}

如果我授权用户并使用提供的访问令牌调用 API,则该用户的声明集合如下所示...

((User as System.Security.Claims.ClaimsPrincipal).Identities.First() as System.Security.Claims.ClaimsIdentity).Claims.ToList()
Count = 10
    [0]: {iss: https://localhost:44375}
    [1]: {aud: https://localhost:44375/resources}
    [2]: {exp: 1468920204}
    [3]: {nbf: 1468916604}
    [4]: {client_id: my_clientid}
    [5]: {scope: openid}
    [6]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: user@domain.com}
    [7]: {http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant: 1468916604}
    [8]: {http://schemas.microsoft.com/identity/claims/identityprovider: idsrv}
    [9]: {http://schemas.microsoft.com/claims/authnmethodsreferences: password}

如果我将正在使用的访问密钥放入 jwt.io 的调试器,我会得到这个...

{
  "iss": "https://localhost:44375",
  "aud": "https://localhost:44375/resources",
  "exp": 1468921471,
  "nbf": 1468917871,
  "client_id": "my_clientid,
  "scope": "openid",
  "sub": "user@domain.com",
  "auth_time": 1468917871,
  "idp": "idsrv",
  "amr": [
    "password"
  ]
}

我不清楚我正在做什么或没有做什么,这会阻止返回定义的声明。

有什么想法吗?

您正在触及 Microsoft 的 JWT 令牌处理程序的默认行为。

Microsoft 认为它知道哪种声明类型最适合您,因此他们会帮您一个忙并即时更改它们(他们是这么认为的)。

您可以接受 - 或者通过在某处(例如在启动时)调用这段漂亮的代码来关闭该行为:

JwtSecurityTokenHandler.InboundClaimTypeMap.Clear()