c# - Request.ServerVariables ["LOGON_USER"] 与 Request.LogonUserIdentity

标签 c# asp.net .net authentication iis

我试图在没有模拟的情况下从 ASP.Net 应用程序的调用方获取当前 WindowsIdentity。

阅读一些文章后,我的设置是:

  • 在我的 IIS 中,我在身份验证设置中启用了 Windows 身份验证
  • 在我的 web.conf 中,我将身份验证模式设置为“Windows”

出于测试目的,我写了以下日志语句

m_techLogger.Warn(string.Format("Request[LOGON_USER] {0}", Request["LOGON_USER"]));
m_techLogger.Warn(string.Format("Request.LogonUserIdentity {0}", Request.LogonUserIdentity.Name));
m_techLogger.Warn(string.Format("HttpContext.Current.User.Identity {0}", HttpContext.Current.User.Identity.Name));
m_techLogger.Warn(string.Format("WindowsIdentity.GetCurrent() {0}", WindowsIdentity.GetCurrent().Name));

此语句返回以下内容

2015-04-23 10:47:19,628 [7] WARN  - Request[LOGON_USER] DOMAIN\User
2015-04-23 10:47:19,681 [7] WARN  - Request.LogonUserIdentity NT AUTHORITY\SYSTEM
2015-04-23 10:47:19,681 [7] WARN  - HttpContext.Current.User.Identity NT AUTHORITY\SYSTEM
2015-04-23 10:47:19,681 [7] WARN  - WindowsIdentity.GetCurrent() NT AUTHORITY\SYSTEM

我了解 WindowsIdentity.GetCurrent().Name 返回系统用户。我不明白为什么 Request.LogonUserIdentity 和 Request[LOGON_USER] 的输出不同。我需要来自用户的 WindowsIdentity 对象,其名称由 Request[LOGON_USER] 返回。

谁能指出我正确的方向?

最佳答案

Request["LOGON_USER"] 只是客户端发送给服务器的身份验证 header 。这意味着它是向您的服务器发送请求的客户端的登录名。除非您激活模拟,否则不会根据 Active Directory 验证此登录名。 更多信息在这里:https://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx

现在,如果不使用模拟,您就会陷入困境。您可以根据服务器上的 AD 检查 Request["LOGON_USER"] 中的用户。但我不建议你这样做。因为恶意客户端可以在该字段中发送任何用户名,如果该用户存在,就会登录到您的服务器。

这样做的正确方法是启用模拟,您使用 AD 组允许用户执行您的服务现在正在执行的操作,您只需将其添加到您的 IIS 配置中即可激活它

<configuration>
  <system.web>
    <identity impersonate="true"/>
  </system.web>
</configuration>

但是如果您真的不能使用模拟,您可以通过使用 Win32 API 模拟服务帐户来摆脱这种情况。 如果你想自己做,这里有来自 Microsoft 的示例 https://msdn.microsoft.com/en-us/library/chf6fbt4.aspxhttps://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx

或者您可以在这里找到一个好的包装器:How do you do Impersonation in .NET?

使用起来就这么简单:

using (new Impersonation(domain, username, password))
{
    // probably connecting to some bad 3rd party stuff that needs a very specific access.
}

现在不知道你这样做的真正原因,我希望这能帮助你走得更远,只有在绝对必要的时候才这样做

关于c# - Request.ServerVariables ["LOGON_USER"] 与 Request.LogonUserIdentity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828567/

相关文章:

asp.net - 我的 pay pal 按钮不会链接到 paypal。它只刷新页面,为什么?

c# - 为什么 .NET 4.0 对该数组的排序方式与 .NET 3.5 不同?

c# - 超出范围后进程仍在运行 - 这安全吗?

c# - 从下拉 Angular 中删除选定值

c# - System.Collections.IEnumerator 对象的意外行为

c# - 如何使用 Entity Framework 获取表中的最新行(考虑性能)?

c# - 仅替换 HTML 标记中的引号的正则表达式

c# - 如何在 SQL Server 查询中将 varchar 转换为十进制?

c# - 使用 Group By 的 LINQ 查询

c# - 有什么方法可以阻止光线转换穿过物体吗?