【问题标题】:How to get the current application pool user in IIS when using impersonate=true?使用impersonate=true时如何在IIS中获取当前应用程序池用户?
【发布时间】:2010-04-30 01:05:30
【问题描述】:

在 .net 中,当网站托管在 IIS 中时,如何获取网站运行的当前用户。即应用程序池用户不是访问该站点的当前用户。

使用集成和模拟的窗口。

<authentication mode="Windows"/>
<identity impersonate="true"/>

【问题讨论】:

  • 有什么用?如果您需要让应用程序池用户执行某些操作,那么您的模拟架构可能不正确。

标签: .net iis windows-authentication


【解决方案1】:

要在托管代码中恢复为应用程序池用户,您可以执行以下操作:

using (WindowsIdentity.Impersonate(IntPtr.Zero)) 
{
   //This code executes under app pool user
}

【讨论】:

【解决方案2】:

找到了解决办法。

使用 RevertToSelf 您可以从线程中剥离模拟。在 IIS 中,这等同于 App Pool 用户。

一些文档

http://www.pinvoke.net/default.aspx/advapi32.reverttoself

http://msdn.microsoft.com/en-us/library/aa379317%28VS.85%29.aspx

还有代码

    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool RevertToSelf();

    private static WindowsIdentity GetAppPoolIdentity()
    {
        WindowsIdentity identity = null;
        Win32Exception win32Exception = null;
        var thread = new Thread(o =>
                        {
                            if (!RevertToSelf())
                            {
                                var win32error = Marshal.GetLastWin32Error();
                                win32Exception = new Win32Exception(win32error);
                            }

                            identity = WindowsIdentity.GetCurrent();
                        });
        thread.Start();
        thread.Join();
        if (win32Exception != null)
        {
            throw win32Exception;
        }
        return identity;
    }

【讨论】:

  • 也许使用 this.Request.LogonUserIdentity.Name
【解决方案3】:

如果您纯粹需要查看用户,那么您不能只使用 Environment.UserName 吗?

我刚刚将我的环境重新配置为使用经典应用程序池(启用模拟)运行,并且用户以 IUSR 的身份出现并启用模拟。

【讨论】:

  • 我实际上想要的是 WindowsIdentity 而不是用户名
【解决方案4】:

John Simons:正是我想要的,谢谢。 VB.net版本:

With System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero)
    Dim sCurrentUserName As String = System.Security.Principal.WindowsIdentity.GetCurrent.Name
End With

【讨论】:

    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多