in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

tanujashares

Impersonation in SharePoint 2007 ......

 

SharePoint security model makes it easy to programmatically execute code within the current user context.

Just write and deploy web part / event handler code and it runs in the security context of the logged in user. There are even built-in functions that take advantage of the user's security context - such as GetSubwebsForCurrentUser() - without requiring any extra coding on our part which is simple yet effective security mechanism.

But there are situations 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.

So here are the two approaches for u ----

Executing code as another named user

Process

When we create a SharePoint site programmatically using the Microsoft.SharePoint namespace, we can supply a user token which enables you to create objects in the context of a specific user. You can impersonate a user by supplying the user token for that user, obtained from the Microsoft.SharePoint.SPUser object. The user token, SPUserToken, is a binary object that contains the identification and domain group membership of a user.

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.

Where to Use -

This Approach is useful to run any code which requires specific permissions to execute that code (like permission for reading a particular list), rather than having a full control access permission.

In such a case, service account can be created by specific access rights just sufficient enough to execute the code.

Caution-

Although impersonation provides a powerful new technique for managing security, it should be used with care to make sure that unwanted activity is not performed by users who shouldn't have the ability to impersonate.

Executing code with elevated privileges

Process

Method 1 -

Elevation of privilege is a new feature of that enables you to programmatically perform actions in code using an increased level of privilege. The Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user.

For example:

1. Define a public method that acts simply as a front end to the method that does the "real" work.

public void ProcessMethod()

{

SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated( ProcessMethodAsElevated);

SPSecurity.RunWithElevatedPrivileges(elevatedMethod);

}

The code uses a method from SPSecurity to indicate the name of the method that will run with Full Control(Basically using Application Pool Account).

In the first line, simply pass in the name of the method as the parameter. In the second line, you execute that method with elevated privileges.

2. Now create the method that does the real work. It is called by the first method (delegate), but executes with Full Control(under Application Pool Account):

private void ProcessMethodAsElevated()

{

//code goes here to do our work

}

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.

Caution-

In this approach, we can't use any SharePoint objects that were created outside the method or else the impersonation won't work.

We also can't use anything like SPControl.GetContextWeb(Context) because that also blows the impersonation out of the water.

Instead, we can tweak it like SPSite site = new SPSite(SPControl.GetContextSite(Context).ID). In this case, we are instantiating a new SPSite object and only using the GUID of the current site. i.e. recreation of the SPSite object with new permissions.

Also, we should dispose of the SPSite object created within the RunWithElevatedPrivileges() before exiting the scope, because that SPSite will still have the SHAREPOINT\system identity even outside of the RunWithElevatedPrivileges() scope.

RunWithElevatedPrivileges() has no effect when running in a standalone exe.

 

----Tanuja

Comments

 

12 Links Today (2007-08-08) said:

Pingback from  12 Links Today (2007-08-08)

August 8, 2007 10:19 AM
 

Links (8/9/2007) « Steve Pietrek’s SharePoint Stuff said:

Pingback from  Links (8/9/2007) « Steve Pietrek’s SharePoint Stuff

August 9, 2007 7:44 PM
 

Raju Indukuri said:

Thanks. I used elevated Privileges option to connect to sql server and used class level variable to hold returned results.

August 15, 2007 1:22 PM
 

Hitesh Chauhan said:

This blog has resolved the issue which other people have been facing for last one year. Thanks man

August 22, 2007 9:33 AM
 

gabriel said:

Remeber the webpart must be in the GAC , if not it doesnt work.

December 9, 2007 5:55 AM
 

Bond, James Bond said:

Great thanks alot!

March 12, 2008 7:06 AM
 

subhadeepdey said:

Hi,

can You please give me the detail how  to call it useing delegate. wnd in which scenerio it causes preble . I am creating a simple page in moss and added this. but it is not working.

June 16, 2008 2:47 AM
 

Ed said:

Hi, I think I want to do something even harder... I want to execute a call to a non-standard "web service". I need to pass the credentials of the current logged in user, but the default credentials belong to the user running the Sharepoint service. Is there anyway of impersonating the current logged in user?

July 9, 2008 4:20 AM
 

Vijander said:

Hi,

Its a great article.It saved a lots of effort

Thanx

September 18, 2008 2:26 AM
 

Rod said:

I tried the Impersonation and get an error still. Do you not need to pass through the Username and Password.

Thank you for your time!!

September 23, 2008 8:15 AM
 

How to access a custom User Site List with SP Object Model « PANVEGAs Blog said:

Pingback from  How to access a custom User Site List with SP Object Model « PANVEGAs Blog

November 18, 2008 3:39 PM

Leave a Comment

(required )  
(optional )
(required )  
Add

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts