如何使用新的 IClaimsTransformation 接口在 .NET 中添加或更改声明

问题描述 投票:0回答:1

我知道

ClaimsAuthenticationManager
用于 .NET Framework。我需要执行一些自定义逻辑来修改声明并确保修改在请求中持续存在

.net asp.net-core asp.net-web-api
1个回答
0
投票

其实很简单。

使用

IClaimsTransformation
是推荐的方法。不要挂钩诸如
Events.OnTokenValidated
之类的事件来修改声明,因为您可能会遇到问题,因为修改后的声明不一定会在请求中持续存在。您可能会发现请求中的
httpContext.User
仍然缺少声明。

另一个优点是这与身份验证类型无关。它在 Jwt、OpenIdConnect 等的管道中执行

这是实现的基本示例。您可以将您可能需要的任何服务注入到构造函数中,例如 dbContext。

TransformAsync 方法将自动调用并传入主体。

public class CustomClaimsTransformation : IClaimsTransformation
{
    private readonly DbContext _dbContext;

    public CustomClaimsTransformation(DbContext dbContext)
    {
        _dbContext = dbContext;
    }
    
    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {       
     var customRoleClaims = new List<Claim>();
    
    //insert here logic to determine custom claims. e.g. does the user have some role that we determine manually, using the database etc
    
    principal.AddIdentity(new ClaimsIdentity(customRoleClaims, JwtBearerDefaults.AuthenticationScheme, null, "roles"));

    }
}

在 Program.cs 中将其注册为 ScopedService:

services.AddScoped<IClaimsTransformation, CustomClaimsTransformation>();

© www.soinside.com 2019 - 2024. All rights reserved.