如何获取当前用户的Windows身份

该站点在我的本地IIS 6.1上运行。 我想添加一些function来从我们的AD中提取信息。 我的AD代码适用于许多其他项目和我的开发服务器。 以下是我写出用户名的尝试:

Response.Write("1. " + this.Request.LogonUserIdentity.Name); Response.Write("2. " + Request.ServerVariables["Auth_User"]); Response.Write("3. " + WindowsIdentity.GetCurrent().Name.ToString()); 

我得到的结果是:

  1. NT AUTHORITY \ IUSR
  2. 管理员
  3. NT AUTHORITY \ NETWORK SERVICE

如何获得实际的Windows用户名,例如我们的域名/用户名

谢谢

此代码段显示了如何设置LogonUserIdentity (使用reflection器)

  if ((this._wr is IIS7WorkerRequest) && (((this._context.NotificationContext.CurrentNotification == RequestNotification.AuthenticateRequest) && !this._context.NotificationContext.IsPostNotification) || (this._context.NotificationContext.CurrentNotification < RequestNotification.AuthenticateRequest))) { throw new InvalidOperationException(SR.GetString("Invalid_before_authentication")); } IntPtr userToken = this._wr.GetUserToken(); if (userToken != IntPtr.Zero) { string serverVariable = this._wr.GetServerVariable("LOGON_USER"); string str2 = this._wr.GetServerVariable("AUTH_TYPE"); bool isAuthenticated = !string.IsNullOrEmpty(serverVariable) || (!string.IsNullOrEmpty(str2) && !StringUtil.EqualsIgnoreCase(str2, "basic")); this._logonUserIdentity = CreateWindowsIdentityWithAssert(userToken, (str2 == null) ? "" : str2, WindowsAccountType.Normal, isAuthenticated); } 

正如您所看到的,IIS 7已经更改了。我相信您正在使用Windows身份validation+模拟,所以我会选择最后一个WindowsIdentity.GetCurrent() ),我确信它是运行的身份请求。

这里有两个不同的Windows用户 – 第一个是您的应用程序用户,第二个是用户(或Windows帐户),您的ASP.NET应用程序(来自IIS透视图的应用程序池)正在其中运行。 WindowsIdentity.GetCurrent通常会返回此引用。

要获取使用该应用程序的实际Windows用户,您必须强制执行身份validation。 为此,您可以在IIS中为该网站启用集成身份validation(Windows身份validation)。 还要修改ASP.NET配置以使用Windows身份validation。 现在您可以使用HttpContext.Current.User.Identity来获取实际用户。

HttpContext.Current.User.Identity可能对您有用。

同样, System.Threading.Thread.CurrentPrincipal可以提供帮助。

但情况可能是您实际上必须在用户登录时设置身份实例(尽管不一定实现IPrincipal和周围机制,而是使用内置的WindowsIdentity实现)。

我不是百分之百的百分之百,Windows身份validation可能会自动设置这个,你只需要检索。

另外,请从MSDN中查看此链接,该链接描述了基本的用户操作,

首先,确保网站位于Intranet区域内(例如, http:// servername /而不是http://www.servername.com/ ),或者您需要将您的FQDN添加到IEs可信站点安全设置。

其次,如果您不使用Intranet区域,请确保IE正在发送凭据 – 工具 – > Internet选项 – >安全 – >自定义级别 – >用户身份validation – >登录 – >使用当前用户名和密码自动登录

用户是否使用其AD域/用户名登录该站点,如果是,请抓取该用户名/域名?

如果不是你将无法得到这个,如果一个随机的网站可以获取当前用户登录的域/用户名,这将是一个巨大的安全问题不是吗?