asp.net-core - 通过 AddIdentityServer 将声明添加到 IdentityServer 设置

标签 asp.net-core jwt identityserver4 openid-connect

我有一个 SPA,它具有 ASP.NET Core Web API 以及使用 AddIdentityServer 打开的内置身份服务器,然后使用 AddIdentityServerJwt:

services.AddIdentityServer()
   .AddApiAuthorization<User, UserDataContext>();
services.AddAuthentication()
   .AddIdentityServerJwt();

我还有一个需要“管理员”角色声明的授权策略设置:

services.AddAuthorization(options =>
{
    options.AddPolicy("IsAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin")); 
});

我有一个使用此策略的 Controller 操作

[Authorize(Policy = "IsAdmin")]
[HttpDelete("{id}")]
public IActionResult Deleten(int id)
{
    ...
}

经过身份验证的用户确实具有“管理员”角色声明:

enter image description here

此身份验证用户的访问 token 似乎不包含管理员声明:

enter image description here

当我尝试使用管理员用户请求此资源时,收到 403 回复:

enter image description here

因此,如果我理解正确的话,IdentityServer 不包含管理员角色声明,因此用户无权访问该资源。

是否可以使用 AddIdentityServerJwt 配置 IdentityServer 使用的声明?或者我是否误解了为什么这不起作用。

最佳答案

其他答案之一非常接近所讨论的特定用例,但忽略了 SPA 的要点。

首先,您必须像已经建议的那样添加 IProfileService 实现:

public class MyProfileService : IProfileService
{
    public MyProfileService()
    { }

    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        //get role claims from ClaimsPrincipal 
        var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);

        //add your role claims 
        context.IssuedClaims.AddRange(roleClaims);
        return Task.CompletedTask;
    }

    public Task IsActiveAsync(IsActiveContext context)
    {
        // await base.IsActiveAsync(context);
        return Task.CompletedTask;
    }
}

但是请继续执行此操作:

services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
                .AddProfileService<MyProfileService>();

您的声明将在 JWT 上公开。将 ClaimTypes.Role 常量替换为与您要公开的声明类型相对应的任何字符串。

关于asp.net-core - 通过 AddIdentityServer 将声明添加到 IdentityServer 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56282355/

相关文章:

asp.net-core - 无效 token - 观众 'empty' 无效

docker - 亚马逊弹性容器服务-与ECS等效的Kubernetes事件/就绪检查

spring-boot - 如何在 Spring 中使用 OAuth2 和 JWT token 代表特定用户调用 protected 资源?

C# .NET Core 托管 Blazor WebAssembly - 将其他客户端添加到 .Server 项目 API

jwt - Azure AD B2C - token 验证不起作用

javascript - 使用 Ed25519 KeyPair 对 JWS(json web 签名)进行签名和验证

c# - 身份服务器 : Add claims to access token in hybrid flow in MVC client

c# - 使用 EPPlus 将 Excel 工作表格式化为表格

c# - Serilog Logcontext 属性在异常处理程序之后消失了

docker - 当对 Trace.WriteLine() 进行多次调用时,在 Linux 容器中运行的 ASP.NET Core 2.0 应用程序会遇到锁定问题