角色 - 身份服务器 4

Ale*_*hin 3 roles claims identityserver4

我有一个使用 Asp.Net Core 2.0 API、Identity Server 和 WPF 应用程序完成的项目。登录后,我可以从 WPF 访问 API。

现在我正在尝试实现角色,以便我能够仅授权某些用户访问 API。

在 Config.cs 中,我声明了我的客户端并添加到范围:

  new Client
            {
             AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.OfflineAccess,
                    "fiver_auth_api",
                    "role"
                },
            AlwaysIncludeUserClaimsInIdToken=true
           }
Run Code Online (Sandbox Code Playgroud)

声明测试用户:

  return new List<TestUser>
        {
            new TestUser
            {
                SubjectId = "", Username = "", Password = "",
                Claims = new List<Claim>
                {
                    new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
                    new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    new Claim(JwtClaimTypes.Role, "Admin"),
                    new Claim(JwtClaimTypes.Scope, "openid offline_access fiver_auth_api")
                }
            }
       }   
Run Code Online (Sandbox Code Playgroud)

在我使用的控制器中:

[Authorize(Roles = "Admin")]
Run Code Online (Sandbox Code Playgroud)

为什么我没有在令牌中获得用户声明?

Ale*_*hin 6

对于感兴趣的人,我是如何修复它的:在您的配置文件中为您的角色添加一个列表:

new ApiResource
 (
   "fiver_auth_api", 
   "Fiver.Security.AuthServer.Api", 
    new List<string> {"role"} <--- Add this line to your API
  )
Run Code Online (Sandbox Code Playgroud)