Home | Blog | Screencasts | Projects
# Saturday, June 13, 2009

By default SharePoint will use impersonation, so the web.config file will have the setting:

<identity impersonate="true" />

 

This means that if you try and connect to a SQL server database from say a custom web part, the connection will appear to SQL server as the user that requested the page. This is very useful if you care about the actual user, so for example if the database has permissions set based on this assumption.

However it is often useful to have just the application pool account connect to the SQL Server database or you may wish to give the application pool account permissions to connect to active directory but not every user.

It this case you will need to impersonate the application pool account. There is a bit of code floating around the web that uses P/Invoke to call ReverToSelf() from the advapi32.dll. It turns out it’s simpler than that:

 

using (HostingEnvironment.Impersonate()) 
{
 
    // access external resource as app pool account
 
}
 

 

The HostingEnvironment.Impersonate() will do the same thing that as a call to RevertToSelf().

 

If you like me and organise your data access calls into nice methods that perform a discrete action such as:

public static void DeleteUser(int userID)
{
 
//do some database access
 
}

 

You might be really loathed to wrap all these methods with the same code like:

public static void DeleteUser(int userID)
{
 
   using(HostingEnvironment.Impersonate())
   {
      //do some database access
   }
}

 

Instead you might like to take a look at what a project such as PostSharp can offer:

 

"You can make your own custom attributes that will really add new behaviors to your code! This is sometimes called aspect-oriented programming (AOP) or policy injection."

 

This means that you can define your own attribute that will have code that will run on any invocation of your code:

public class ImpersonateAttribute : OnMethodInvocationAspect
{
    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
        using(HostingEnvironment.Impersonate())
        {
            eventArgs.Proceed();
        }
    }
}

 

So our code then looks like this:

[ImpersonateAttribute]
public static void DeleteUser(int userID)
{
   //do some database access    
}

 

Much easier to maintain. Now every bit of code with this attribute will run as the application pool account.

Saturday, June 13, 2009 11:16:09 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
code | Sharepoint
Tracked by:
"TIP: Accessing Resources as the Web Application Pool Account Instead of the Cu... [Trackback]
Statistics
Total Posts: 191
This Year: 0
This Month: 0
This Week: 0
Comments: 41