Using SharePoint it’s easy to run a block of code with elevated permissions:
using (SPSite elevatedSite = new SPSite(siteId))
using (SPWeb elevatedWeb = elevatedSite.OpenWeb(wedId))
// operations using elevated SPWeb object...
This is fine for SharePoint related impersonations. Any code executed within the elevated block that authenticates using an object instantiated outside the RunWithElevatedPrivileges block will run using the context of the current user and not the elevated account. So for example, if you wanted to make a web method call using a single user (or connect to a database) and not the current context, the following code block will achieve this for you:
This is a post that I’d imagine most people who have been developing with SharePoint will be aware of but I thought it might be worthwhile blogging about.
I’ve seen code where people have tried to impersonate a user to perform actions against a SharePoint file by using the LogonUser function.
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
When working with SharePoint, there is no need for this. For starters, the above function requires you to know the user’s password. Now, of course, there are good reasons why the business rules may require this and I’m not saying it shouldn’t be implemented that way. For the scenarios where this is not required, there’s a very easy and simple way of impersonating a valid SharePoint user, without having to know their password.