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

调用受保护WebAPI控制器时认证失败:颁发者'(null)'无效

解决WebAPI认证时“颁发者'(null)'无效”的问题

这个错误核心是JWT认证流程中,Token的颁发者(iss声明)为空,或者WebAPI的认证配置未匹配到有效颁发者。以下是具体解决步骤:

  • 检查WebAPI的JWT认证配置
    在项目配置文件(如Program.cs或Startup.cs)中,确保AddJwtBearer的TokenValidationParameters正确设置颁发者验证规则:

    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                // 单个有效颁发者
                ValidIssuer = "https://your-auth-server.com",
                // 多个有效颁发者用数组
                // ValidIssuers = new[] { "issuer1", "issuer2" },
                ValidateAudience = true,
                ValidAudience = "your-api-audience",
                ValidateLifetime = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-signing-key"))
            };
        });
    

    注意ValidIssuer的值必须和Token生成端的颁发者完全一致,包括协议、域名等细节。

  • 确认Token生成端的iss声明不为空
    检查生成JWT的服务(如IdentityServer、自定义Token逻辑),确保iss字段被正确赋值:

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Issuer = "https://your-auth-server.com", // 必须明确设置
        Audience = "your-api-audience",
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = new SigningCredentials(
            new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-signing-key")),
            SecurityAlgorithms.HmacSha256Signature)
    };
    var tokenHandler = new JwtSecurityTokenHandler();
    var token = tokenHandler.CreateToken(tokenDescriptor);
    

    可以用JWT解析工具验证生成的Token,确认iss字段存在且不为空。

  • 检查请求中的Token格式
    确保前端请求时,Authorization头格式为Bearer {Token},无多余空格或字符,Token未被截断或篡改。

  • 临时调试(仅开发环境)
    若只是开发阶段测试,可暂时关闭颁发者验证(生产环境绝对禁止):

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        // 其他配置...
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:06:05