如何在 JWT 中包含对身份角色的声明?

How to include claim on Identity Roles in JWT?

我已经按照 Microsoft (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.0) 的模板和说明在我的 Asp.Net 核心 Web API 应用程序中实施了身份验证和授权。

在身份验证 JWT 令牌中,我想包含一个包含用户身份角色的声明,这样我就可以轻松地在我的 SPA 客户端应用程序中隐藏不必要的模块,并在 API 控制器上快速授权.但是,默认的 JWT 不包含对角色的声明。

在我目前使用的中间件中,我可以配置 JWT 令牌以包含角色声明吗? 注意我还没有创建任何定义对于当前令牌,中间件会自动为我创建令牌。

编辑 我已经更改了配置,因此该角色是对用户的声明。此外,我的配置已更改,因此范围包括此声明。生成的令牌仍然不包含角色。

我的主应用程序同时托管 Web API 和身份验证服务器。套餐:

<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0" />

启动:

...
services.AddDefaultIdentity<AppUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<DbContext>();

services.AddAuthentication()
        .AddIdentityServerJwt();

services.AddIdentityServer()
    .AddApiAuthorization<PimUser, PimDbContext>(options =>
    {
        options.IdentityResources.Add(new IdentityResource(
            name: "roles",
            displayName: "Roles",
            claimTypes: new List<string>{"role"}) { Required = true});
        options.Clients.AddSPA("authAngular", spa =>
            spa.WithScopes("AppAPI", "openid", "profile", "roles")
                .WithClientId("pimAngular")
                .WithRedirectUri("https://localhost:5001/authentication/login-callback")
                .WithLogoutRedirectUri("https://localhost:5001/authentication/logout-callback"));
    });
...

app.UseAuthentication(); 
app.UseAuthorization(); 
app.UseIdentityServer();
...

用户被添加到角色,同时声明被添加:

await userManager.AddToRolesAsync(user, role);
await userManager.AddClaimAsync(user, new Claim("role", role));

openid 的配置确实包括新范围:

"scopes_supported": [
    "openid",
    "profile",
    "roles",
    "AppAPI",
    ...
],
"claims_supported": [
    ...
    "role"
]

当我查询 authClient 的配置时,我也得到了正确的范围:

{
  "authority": "https://localhost:5001",
  "client_id": "authAngular",
  "redirect_uri": "https://localhost:5001/authentication/login-callback",
  "post_logout_redirect_uri": "https://localhost:5001/authentication/logout-callback",
  "response_type": "code",
  "scope": "AppAPI openid profile roles"
}

生成的令牌仍然不包含角色声明。我错过了什么?

编辑后的配置确实有效,但只有在创建新数据库并删除所有以前的迁移之后。一定是有什么腐败的 data/scheme 把我搞砸了。