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

如何在ASP.NET Core中配置<identity impersonate="true" />及获取Windows登录用户

解决IIS部署ASP.NET Core获取Windows登录用户及身份模拟问题

一、让System.Security.Principal.WindowsIdentity.GetCurrent().Name返回Windows登录用户

要获取访问者的Windows登录账户,需完成以下配置:

  1. IIS站点设置

    • 打开IIS管理器,进入目标站点的「身份验证」功能
    • 禁用「匿名身份验证」,启用「Windows身份验证」
    • 应用池标识保持默认ApplicationPoolIdentity即可(若需访问跨服务器资源,再根据需求调整)
  2. ASP.NET Core项目配置

    • 在Program.cs中注册Windows身份验证服务:
      builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);
      
    • 确保中间件管道中添加认证和授权:
      app.UseAuthentication();
      app.UseAuthorization();
      
    • 默认情况下WindowsIdentity.GetCurrent()仍返回应用池账户,若要让它返回登录用户,必须启用身份模拟(见下文)。日常业务中更推荐使用HttpContext.User.Identity.Name直接获取登录用户信息,无需模拟。

二、ASP.NET Core中实现类似<identity impersonate="true" />的身份模拟

ASP.NET Core没有WebForms中直接的<identity impersonate="true"/>配置项,需通过代码逻辑实现身份模拟:

  1. 基础配置

    • 已完成上文的Windows身份验证启用步骤
    • 在Program.cs中添加HttpContext访问器(用于获取当前用户身份):
      builder.Services.AddHttpContextAccessor();
      
  2. 代码中实现模拟
    在需要以登录用户身份执行的代码块中,使用WindowsImpersonationContext实现模拟:

    using System.Security.Principal;
    using Microsoft.AspNetCore.Http;
    
    // 注入IHttpContextAccessor获取当前上下文
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    public YourService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    
    public void ExecuteWithImpersonation()
    {
        var windowsIdentity = _httpContextAccessor.HttpContext.User.Identity as WindowsIdentity;
        if (windowsIdentity != null)
        {
            // 开启身份模拟
            using (var impersonationContext = windowsIdentity.Impersonate())
            {
                // 此代码块内的操作将以登录用户身份运行
                var currentUser = WindowsIdentity.GetCurrent().Name; // 返回登录用户名称
                // 执行你的业务逻辑
            }
        }
    }
    
  3. IIS额外配置

    • 进入应用池的「高级设置」,将「加载用户配置文件」设为True
    • 若需访问网络资源,需为登录用户或应用池账户分配对应权限

注意事项

  • 身份模拟会带来性能损耗,仅在必须以用户身份访问资源时使用
  • 若涉及跨服务器资源访问,需配置Kerberos约束委派解决「双跳问题」
  • 确保服务器的Windows身份验证服务(NTLM/Kerberos)正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:30:52