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

dev*_*r82 2 identityserver4

我按照文档中的示例编写了一个小型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")
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用ResourceOwnerPassword流程获得了访问令牌。并且我有权访问我的API。

问题在于,当在受保护的API中尝试获取用户身份时,name属性返回为null,并且看不到电子邮件声明。不管我做什么,我总是会看到相同的12个主张。该sub要求是唯一一个与我放在了信息传递Client的对象。

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

raw*_*wel 5

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

  1. 您需要使用访问令牌中所需的声明来定义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"
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)
  1. 然后,您允许资源所有者客户端访问那些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"
                }
            },
Run Code Online (Sandbox Code Playgroud)
  1. 然后,您可以在roclient中请求范围

     client.RequestResourceOwnerPasswordAsync("bob", "bob", "api2.read_only", optional).Result
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将访问令牌发布到API,您将获得添加到API资源的声明。

在此处输入图片说明