You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET7中为AddMicrosoftIdentityWebApi配置自定义JwtBearerHandler

.NET7中配置自定义JwtBearerHandler替代AddMicrosoftIdentityWebApi的方法

如果你想替换默认的AddMicrosoftIdentityWebApi,改用自定义的JwtBearerHandler,可以按照以下步骤操作:

1. 实现自定义JwtBearerHandler

首先创建继承自JwtBearerHandler的自定义处理器,重写需要自定义逻辑的方法:

public class CustomJwtHandler : JwtBearerHandler
{
    public CustomJwtHandler(IOptionsMonitor<JwtBearerOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
        // 可在此注入额外服务或初始化自定义逻辑
    }

    // 重写HandleAuthenticateAsync实现自定义验证流程
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // 先执行基类的默认JWT验证逻辑
        var baseResult = await base.HandleAuthenticateAsync();

        if (baseResult.Succeeded)
        {
            // 示例:添加自定义Claims
            var updatedIdentity = new ClaimsIdentity(baseResult.Principal.Identity);
            updatedIdentity.AddClaim(new Claim("Custom_Claim", "Custom_Value"));
            
            var updatedPrincipal = new ClaimsPrincipal(updatedIdentity);
            return AuthenticateResult.Success(new AuthenticationTicket(updatedPrincipal, baseResult.Properties, Scheme.Name));
        }

        // 验证失败时返回原结果
        return baseResult;
    }
}

2. 替换原有的认证服务注册

将原本的builder.Services.AddAuthentication().AddMicrosoftIdentityWebApi(builder.Configuration)替换为手动注册自定义方案:

builder.Services
    .AddAuthentication("AzureAd") // 设置默认认证方案为AzureAd
    .AddScheme<JwtBearerOptions, CustomJwtHandler>(
        "AzureAd", 
        options => builder.Configuration.Bind("AzureAd", options)
    );

3. 确保配置节点正确

你的appsettings.json中需要保留AzureAD的配置节点,示例如下:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your-domain.onmicrosoft.com",
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",
    "Audience": "your-api-audience"
  }
}

可选:补充原Microsoft Identity Web的配置项

如果需要保留原AddMicrosoftIdentityWebApi中的部分默认配置(比如Claims映射规则),可以手动在options中添加:

options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "role";
// 根据需求添加其他验证参数配置

内容的提问来源于stack exchange,提问作者user441365

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:48:17