Impersonation Class

on August 22, 2006

Hi,

Here is my impersonation Class. I took it from somewhere else, sorry if I can’t put the name of the author.

I did some modifications to fix one or two bugs and added two kinf of whoami methods. It is now working great. Hope that’l be usefull to some of you guys.

Code:

using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Web;
namespace Ns.Services.Utilities.SharepointTools
{
public class ImpersonationUsingRevertToAppPool
{
WindowsIdentity currentUser = null;
bool reverted = false;
//Declare API DLLs (like in VB6).
[DllImport("advapi32.dll")]
static extern bool RevertToSelf();
//Capture the current user's
//WindowsIdentity when constructed
//so you know who to impersonate later.
public ImpersonationUsingRevertToAppPool()
{
currentUser =
WindowsIdentity.GetCurrent();
}
//Revert to the original application pool's
//security context. Only do this if
// you aren't already running in that context.
//RevertToSelf will return True if successful
//so throw an exception if it returns False.
public void UseAppPoolIdentity()
{
if (!WindowsIdentity.GetCurrent().IsSystem)
{
if (RevertToSelf())
{
reverted = true;
WindowsIdentity.GetCurrent().Impersonate();
}
else
{
throw new
System.Security.SecurityException();
}
}
}
//Return to impersonating the
//authenticated user.
//Anonymous users are impersonated
//as IUSR_machinename, by default.
public void ReturnToImpersonatingCurrentUser()
{
if(reverted)
{
currentUser.Impersonate();
}
}
/// Help in debugging situation.
public string WhoAmI()
{
return WindowsIdentity.GetCurrent().Name;
}
/// Help in debugging situation.
public string WhoAmIUsingHTTPRequest()
{
return HttpContext.Current.Request.ServerVariables["LOGON_USER"];
}
}
}

Here is a link to a zip file containeing the class.

ImpersonationUsingRevertToAppPool

ShareThis