c# - asp.net webapi Windows 身份验证在模拟呼叫中获取用户名
问题描述
出于某种原因,我无法在模拟呼叫中获取 Windows 用户名。我已经按照 这里的答案,但没有得到相同的结果。
在服务器 AI 上有一个 Intranett ASP.MVC 应用程序,在 IIS 中只有 Windows 身份验证。
在服务器 A 上的 mvc 应用程序的 Web 配置中,我使用模拟。
调用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) 项目
在服务器 B 上的 Web api 的 Web 配置中,指定使用 Windows 身份验证,而不是模拟。
我正在尝试为浏览我的 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 用户名呢?
解决方案
推荐阅读
- python - 访问列表字典中列表的最小元素
- python - Mac M1 中损坏的 Python
- android - Android 上的 Expo 图像压缩
- angular - 在页面上添加相同 Angular 元素的两个实例会中断路由
- c# - 有没有办法根据向导中的用户输入从 Visual Studio 项目模板中排除文件?
- javascript - 服务器集成测试
- c# - 如何解决 INSERT 语句与 FOREIGN KEY 约束“FK_Tickets_AspNetUsers_UserId”冲突
- dataframe - 加载多个 xls 文件、编辑和附加到一个数据帧中
- javascript - 如何在 Javascript 中组合函数
- apache-spark - Spark 到 JDBC:Py4JJavaError - 连接已启动,但没有一个提供者