首页 > 解决方案 > asp.net webapi Windows 身份验证在模拟呼叫中获取用户名

问题描述

出于某种原因,我无法在模拟呼叫中获取 Windows 用户名。我已经按照 这里的答案,但没有得到相同的结果。

在服务器 AI 上有一个 Intranett ASP.MVC 应用程序,在 IIS 中只有 Windows 身份验证。 IIS 服务器 A

在服务器 A 上的 mvc 应用程序的 Web 配置中,我使用模拟。

Web.config,服务器 A

调用web api的代码

var impersonationContext = WindowsIdentity.GetCurrent().Impersonate();
using (impersonationContext)
{
   var client = GetHttpClient();
   return await client.PostAsync("services/ExecuteCommand/Execute", httpContent);
}
private HttpClient GetHttpClient()
{
   var httpClientHandler = new HttpClientHandler
   {
      UseDefaultCredentials = _commandServiceUseDefaultCredentials
   };
   var client = new HttpClient(httpClientHandler)
   {
      BaseAddress = new Uri(ConfigurationManager.AppSettings["CommandServiceBaseUrl"].ToString()),
   };
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));       
   return client;
}

在服务器 B 上,我有一个带有 Windows 身份验证的 ASP.Net Web API (Core) 项目

IIS 服务器 B

在服务器 B 上的 Web api 的 Web 配置中,指定使用 Windows 身份验证,而不是模拟。

Web.config,服务器 B

我正在尝试为浏览我的 mvc 应用程序的人获取 Windows 用户名。我已经尝试了很多,所以我最终用这种方法来获得它们。

private string GetUserName()
{
   var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
   System.Security.Principal.WindowsIdentity windowsIdentity2 = null;
   if (System.ServiceModel.OperationContext.Current != null)
      if (System.ServiceModel.OperationContext.Current.ServiceSecurityContext != null)
         windowsIdentity2 = System.ServiceModel.OperationContext.Current.ServiceSecurityContext.WindowsIdentity;

   var httpContextIdentity = System.Web.HttpContext.Current.User.Identity;
   return string.Format("{0}_{1}_{2}_{3}_{4}",
                System.Environment.UserName ?? "",
                User.Identity.Name,
                windowsIdentity != null ? windowsIdentity.Name : string.Empty,
                windowsIdentity2 != null ? windowsIdentity2.Name : string.Empty,
                httpContextIdentity != null ? httpContextIdentity.Name : string.Empty);
}

这产生了这个结果

System.Environment.UserName:ServerB App_pool 用户无域

User.Identity.Name:域\ServerA$

System.Security.Principal.WindowsIdentity.GetCurrent().Name:ServerB 域\app_pool 用户

System.ServiceModel.OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name:(空)

System.Web.HttpContext.Current.User.Identity:域\ServerA$

那么如何获取我的 mvc 应用程序的最终用户的 Windows 用户名呢?

标签: c#asp.netasp.net-mvcwindows-authenticationimpersonation

解决方案


推荐阅读