Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I turn off impersonation just in a couple instances

I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write.

What I want to do is turn off impersonation for just a couple commands.

Is there a way to do something like this?

using(HostingEnvironment.Impersonate.Off())
  //I know this isn't a command, but you get the idea?

Thank you.

like image 558
naspinski Avatar asked Sep 24 '08 02:09

naspinski


2 Answers

Make sure the Application Pool do have the proper rights that you need.

Then, when you want to revert to the application pool identity... run the following:

private WindowsImpersonationContext context = null;
public void RevertToAppPool()
{
    try
    {
        if (!WindowsIdentity.GetCurrent().IsSystem)
        {
            context = WindowsIdentity.Impersonate(System.IntPtr.Zero);
        }
    }
    catch { }
}
public void UndoImpersonation()
{
    try
    {
        if (context != null)
        {
            context.Undo();
        }
    }
    catch { }
}
like image 158
Maxime Rouiller Avatar answered Sep 27 '22 19:09

Maxime Rouiller


I am not sure if this is the preferred approach but when I wanted to do this I new'd up an instance of a WindowsIdentity and called the Impersonate method. This allows subsequent code to impersonate a different Windows user. It returns a WindowsImpersonationContext that has an Undo method which reverts the impersonation context back again.

like image 41
jedatu Avatar answered Sep 27 '22 20:09

jedatu