CJ

The circle of life – ** .Net – Training – MOSS **

  • Past Post

  • Vistor Locations

Run code under the IIS authenticated user context

Posted by Clayton James on September 4, 2006

This is a blog post that I will refer back to many times, hence the reason I am writing it.

Everytime I am developing an ASP.NET application that has to handle some Windows privileges (like copying files to a UNC location) I have to look up the required code. I have found myself wasting time doing this and I am sure the next time I am doing an ASP.NET app that requires this process I will have forgotten, so now I will know exactly where to look.

Programmatically copying files to a network share requires a neat little peice of code. This code is required as ASP.NET code doesn’t run under the IIS authenticated user, it runs under the local ASPNET account which will only have certain privileges. Of course  you could manully provide the required privileges to this account but I feel this is a messy solution that could provide greater security risks (I have seen this done: local admin to write to the registry). So, if you ever want to impersonate the IIS authenticated user to perform a certain task and then revert back to the local ASPNET user account then this little code snippet will come in very handy.

using System.Security.Principal;

if (User.GetType() == typeof(WindowsPrincipal))
{
WindowsIdentity id = (WindowsIdentity) User.Identity;
WindowsImpersonationContext impersonate = id.Impersonate();

//perform tasks under the impersonated user
//*** ***//

//revert back to local ASPNET account
impersonate.Undo();
}
else
{
//user isn’t authenticated
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: