Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Thursday, December 01, 2011

Impersonation in SharePoint

Impersonation is used when the code needs to be executed with permissions
greater than that of the current user (like instantiating a site collection
or enumerating list permissions or reading a lookup / configuration list on
which user may not have access rights).

In such situations, the code needs to be executed with elevated permission
level or under the context of user with higher permissions i.e.
Impersonation.
There are two methods available:

*Method 1*
**

This allows you to use the Microsoft.SharePoint.SPSite constructor to
instantiate a site collection object that runs as if that user was making
changes.
SPSite site = new SPSite("SiteCollection_Url");
SPWeb web = site.OpenWeb();
SPUser user = web.AllUsers["User_Name"];
SPUserToken token = user.UserToken;
SPSite impersonatedSiteCollection = new SPSite("SiteCollection_Url", token);

Any objects (SPWeb, SPList, etc) that you create from this impersonated site
collection will execute as the impersonated user.

*Method 2*
**
We can also implement this method by creating dummy delegate method within a
code.

SPSecurity.RunWithElevatedPrivileges(delegate()
{

     //code goes here to do our work

});
*Where to Use -*
**
This approach can be used in scenarios to read or update Site Collection,
Site related objects using Full control in event handlers, features or web
parts (i.e. code being executed under SharePoint Context.

No comments:

Post a Comment