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

IIS启用匿名+Windows身份验证时ASP.NET Core 2.2如何获取Windows登录用户名

问题根因

  1. 同时启用匿名和Windows认证时,IIS默认优先走匿名身份处理请求,不会主动要求客户端传递Windows登录凭证,因此User.Identity.Name返回null
  2. System.Security.Principal.WindowsIdentity.GetCurrent().Name获取的是Web应用进程的运行身份,也就是你配置的应用池标识,而非访问用户的身份,IIS Express下正常只是因为Express默认用当前登录的Windows用户运行进程,属于巧合,正式环境这个方法永远不能用来取访问用户身份

解决步骤

1. 调整应用代码配置

首先在你的Startup.cs文件中修改配置:

  • 确保已经安装NuGet包:Microsoft.AspNetCore.Authentication.IIS
  • ConfigureServices方法中添加身份验证服务:
public void ConfigureServices(IServiceCollection services)
{
    // 其他服务配置
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
  • Configure方法中启用身份验证中间件,注意顺序要放在UseMvc之前:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // 其他中间件配置
    app.UseAuthentication();
    app.UseMvc();
}

2. 调整IIS部署配置

  • 确认站点的「身份验证」设置中,Windows身份验证和匿名身份验证都处于启用状态
  • 打开Windows身份验证的「高级设置」,确认勾选「内核模式身份验证」,提供程序列表中按优先级排列协商、NTLM
  • 检查站点根目录下的web.config文件,aspNetCore节点需要添加forwardWindowsAuthToken="true"配置,示例:
<aspNetCore processPath="dotnet" arguments=".\你的应用名.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />

3. 接口适配逻辑

如果你的接口需要同时支持匿名访问、且存在Windows身份时能获取到用户名,可以有两种实现方式:

方案A:主动触发身份验证

在需要获取Windows用户的接口中,先判断身份是否已验证,未验证的话返回401挑战,域内客户端会自动传递当前登录的Windows凭证:

[AllowAnonymous]
[HttpGet("getusername")]
public IActionResult GetUserName()
{
    if (!User.Identity.IsAuthenticated)
    {
        // 触发Windows认证挑战,客户端会自动提交身份凭证
        return Challenge();
    }
    return Ok(User.Identity.Name);
}

方案B:前端请求携带凭证

如果是前端调用接口,需要在请求配置中开启凭证携带,否则浏览器不会自动传递Windows身份凭证:

  • Axios配置:
axios.get('/api/getusername', { withCredentials: true })
  • jQuery AJAX配置:
$.ajax({
    url: '/api/getusername',
    xhrFields: { withCredentials: true }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:54:01