gpt4 book ai didi

identityserver4 - IdentitySever4 用户声明和 ASP.NET User.Identity

转载 作者:行者123 更新时间:2023-12-03 03:40:37 27 4
gpt4 key购买 nike

我按照文档中的示例编写了一个小型 IdentityServer 演示服务器。我有以下 TestUser:

new TestUser
{
SubjectId = "1",
Username = "Username",
Password = "password",
Claims = new List<Claim>()
{
new Claim(System.Security.Claims.ClaimTypes.Name, "Username"),
new Claim(System.Security.Claims.ClaimTypes.Email, "username@domain.com")
}
}

我使用 ResourceOwnerPassword 流程获取访问 token 。并且我有权访问我的 API。

问题是,当我在 protected API 中尝试获取用户身份时,名称属性返回为 null,并且我看不到电子邮件声明。无论我做什么,我总是看到同样的 12 条声明。 sub 声明是唯一与我放入 Client 对象中的信息一起传递的声明。

如何填充 HttpContext.User.Identity.Name 属性并发送有关用户的其他声明/数据?

最佳答案

原因可能是您没有为您的客户请求适当的资源/范围。

  1. 您需要使用访问 token 中所需的声明来定义 API 资源。

例如,在 Resources.cs 中,您可以添加要包含在所有 api2 范围中的声明

        new ApiResource
{
Name = "api2",

ApiSecrets =
{
new Secret("secret".Sha256())
},

UserClaims =
{
JwtClaimTypes.Name,
JwtClaimTypes.Email
},

Scopes =
{
new Scope()
{
Name = "api2.full_access",
DisplayName = "Full access to API 2",
},
new Scope
{
Name = "api2.read_only",
DisplayName = "Read only access to API 2"
}
}
}
  • 然后,您允许资源所有者客户端访问这些 API 资源。
  • 例如在 client.cs 中

            new Client
    {
    ClientId = "roclient",
    ClientSecrets =
    {
    new Secret("secret".Sha256())
    },

    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

    AllowOfflineAccess = true,
    AllowedScopes =
    {
    IdentityServerConstants.StandardScopes.OpenId,
    "custom.profile",
    "api1", "api2.read_only"
    }
    },
  • 然后您可以在 roclient 中请求范围

     client.RequestResourceOwnerPasswordAsync("bob", "bob", "api2.read_only", optional).Result
  • 将访问 token 发布到 API,您将获得添加到 API 资源的声明。

  • enter image description here

    关于identityserver4 - IdentitySever4 用户声明和 ASP.NET User.Identity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43629216/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com