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

Phi*_*hil 9 c# asp.net authentication username kentico

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

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

我得到的结果是:

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

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

谢谢

Vin*_*ayC 15

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

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


Ali*_*tad 2

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

 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);
        }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这已针对 IIS 7 进行了更改。我相信您正在使用Windows 身份验证 + 模拟,因此我将使用最后一个( WindowsIdentity.GetCurrent()),我确信它是正在运行的身份请求。