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

.NET Core 3.1 API Postman Windows认证时User.Identity.Name为空及认证报错问题

问题排查解决步骤

1. 修正认证服务注册配置

你遇到的No DefaultChallengeScheme found报错,核心原因是仅指定了默认认证方案,未注册对应方案的处理程序,也未显式指定质询方案。根据你的托管模式选择对应配置:

  • 若使用IIS/IIS Express托管(对应launchSettings里的iisSettings配置),修改ConfigureServices代码如下:
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = IISDefaults.AuthenticationScheme;
    })
    .AddIISIntegration();
    // 保留其余原有配置
}
  • 若使用Kestrel自托管(控制台启动模式),launchSettings的iisSettings不生效,改用如下配置:
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
        .AddNegotiate();
    // 保留其余原有配置
}

同时需要在Program.cs中添加Kestrel的Windows认证配置:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>()
            .ConfigureKestrel(options =>
            {
                options.ConfigureEndpointDefaults(listenOptions =>
                {
                    listenOptions.UseHttps();
                    listenOptions.Authentication.Schemes = Microsoft.AspNetCore.Server.Kestrel.Core.AuthenticationSchemes.Negotiate | Microsoft.AspNetCore.Server.Kestrel.Core.AuthenticationSchemes.NTLM;
                    listenOptions.Authentication.AllowAnonymous = false;
                });
            });
        });

2. 确认启动模式匹配配置

launchSettings.json中的iisSettings仅对IIS/IIS Express启动模式生效,如果你直接选择项目名启动(Kestrel自托管),Windows认证配置不会生效,会直接导致User.Identity.Name为空。启动时请选择对应模式:

  • 用IIS托管配置就选IIS Express启动
  • 用Kestrel配置就选对应项目名启动

3. 无[Authorize]标签时Name为空的原因

当匿名认证未完全关闭、或认证中间件未触发时,未加[Authorize]标签的接口不会强制走认证流程,因此不会填充用户身份信息。测试阶段建议给接口加上[Authorize]特性,强制触发认证逻辑。

4. Postman配置修正

  • 认证类型选择NTLM Authentication,不要选其他类型
  • 域用户的用户名格式为域名\用户名,本地用户直接填用户名即可
  • 本地调试时不要用localhost作为访问地址,改用你的计算机名,避免Postman不发送NTLM凭证的问题
  • 若部署到正式IIS,需确认IIS站点的身份验证配置:开启Windows认证、关闭匿名认证,且Windows认证的提供程序中NTLM优先级高于Negotiate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:15:03