views:

211

answers:

3

In .net when a website hosted in IIS how do you get the current user the website is running under. ie the Application Pool user not the the current user accessing the site.

Using windows integrated and impersonate.

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

If you purely need to see the user then couldn't you just use 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.

Paul Farry
I actually want the WindowsIdentity not the username
Simon
A: 

Found a solution.

Using RevertToSelf you can strip the impersonation from a thread. In IIS this equates to the App Pool user.

Some doco

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

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;
    }
Simon
+1  A: 

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
}
John Simons