我已按照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","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"
}
生成的令牌仍不包括角色声明。我想念什么?