c# - claim 类型不正确

标签 c# asp.net-core identityserver4

我目前正在开发 API。 token 从 IdentityServer4 返回。

我正在尝试从 token 声明中取回子 ID,即当前授权用户的 ID。我可以在此处的声明中看到它。

{
  "nbf": 1512632838,
  "exp": 1512636438,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "testapi"
  ],
  "client_id": "ServiceAccountAccess",
  "sub": "21248582",
  "auth_time": 1512632823,
  "idp": "local",
  "name": "TestUser",
  "resource_id": "21260601",
  "xena_fiscal_id": "21875",
  "fiscal_name": "My company",
  "picture_url": "/Content/images/avatar-company-xena.jpg",
  "application_id": "16140911",
  "scope": [
    "openid",
    "profile",
    "testapi"
  ],
  "amr": [
    "password"
  ]
}

我的 API 调用非常简单

    [Authorize]
    public async Task<ActionResult> ChangeFiscal([FromBody] long fiscalId)
    {

        var name = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
            .Select(c => c.Value).SingleOrDefault();

    }

我不明白为什么 sub 或 subject 会变成

"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"

enter image description here

我可以从 api 中看到它已经完成了相当多的声明

{
  "nbf": 1512653706,
  "exp": 1512657306,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "testapi"
  ],
  "client_id": "ServiceAccountAccess",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "21248582",
  "auth_time": 1512652100,
  "http://schemas.microsoft.com/identity/claims/identityprovider": "local",
  "name": "TestUser",
  "supporter": "21248582",
  "http://schemas.microsoft.com/claims/authnmethodsreferences": "password",
  "resource_id": "21527443",
  "xena_fiscal_id": "21876",
  "fiscal_name": "this",
  "picture_url": "/Content/images/avatar-company-xena.jpg",
  "scope": [
    "openid",
    "profile",
    "testapi"
  ]
}

最佳答案

花了一个小时才弄清楚 Microsoft JWT 处理程序将这些标准声明转换为 Microsoft 专有声明。

通过将以下行添加到启动配置方法中,我能够关闭这个烦人的“功能”

JwtSecurityTokenHandler.InboundClaimTypeMap.Clear()

关于c# - claim 类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696872/

相关文章:

c# - ServiceStack 响应默认值

c# - 使用 SQL Server 创建和回滚测试数据

asp.net-core - 将内容加载到 Blazor TabControl

iis - 如何在 ASP vNext 中使用 session

c# - 当 UserLogin 存在时,ExternalLoginSignInAsync 返回失败响应

c# - .Net 核心 API 返回 405 :Method not allowed when having Authorize attribute

c# - 混淆删除数据上下文类

c# - 重复代码位的设计模式/C#技巧

c# - Identity Server 4 在 IConfigurationDbContext 上没有 SaveChanges 方法

api - 生成访问 token 并通过 Azure API 管理针对 IdentityServer4 进行验证