简体   繁体   English

使用 impersonate=true 时如何获取 IIS 中的当前应用程序池用户?

[英]How to get the current application pool user in IIS when using impersonate=true?

In .net when a website hosted in IIS how do you get the current user the website is running under.在 .net 中,当网站托管在 IIS 中时,您如何获取网站正在运行的当前用户。 ie the Application Pool user not the the current user accessing the site.即应用程序池用户不是访问该站点的当前用户。

Using windows integrated and impersonate.使用 windows 集成和模拟。

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

To revert to the app pool user in managed code you can do the following:要在托管代码中恢复为应用程序池用户,您可以执行以下操作:

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

Found a solution.找到了解决办法。

Using RevertToSelf you can strip the impersonation from a thread.使用 RevertToSelf 您可以从线程中去除模拟。 In IIS this equates to the App Pool user.在 IIS 中,这等同于应用程序池用户。

Some doco一些文件

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

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

And the code和代码

    [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;
    }

If you purely need to see the user then couldn't you just use Environment.UserName?如果您纯粹需要查看用户,那么您不能只使用 Environment.UserName 吗?

I just reconfigured my environment to run with a Classic App pool (with Impersonation on) and the User comes out as IUSR with Impersonate on.我刚刚重新配置了我的环境以使用经典应用程序池运行(启用模拟),并且用户作为 IUSR 出现并启用模拟。

John Simons: Exactly what I wanted, Thanks.约翰西蒙斯:正是我想要的,谢谢。 For VB.net version:对于 VB.net 版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM