How to get the current application pool user in IIS when using impersonate=true?
-
02-10-2019 - |
Question
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"/>
Solution
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
}
OTHER TIPS
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;
}
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.
John Simons: Exactly what I wanted, Thanks. For VB.net version:
With System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero)
Dim sCurrentUserName As String = System.Security.Principal.WindowsIdentity.GetCurrent.Name
End With