Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Impersonation in SharePoint 2010

Posted by JP on October 2, 2012


In this article we can explore the methods of Impersonation inside SharePoint 2010.

What is Impersonation?

Impersonation is the security feature that enables to control the Identity under which code is executed. Impersonation gives the following advantages:

· Run a high privilege code through a low privilege user

· Record changes in account of another user

image

Example

A web part has to execute code that will update a List.  There are many users using this web part but they all do not have write permission on the list.  As the web part code is getting executed in the user’s context, exception occurs for some users.

Using Impersonation we can elevate the code privilege to high so that no exception occurs.

What are the Impersonation methods in SharePoint 2010?

SharePoint 2010 provides the following methods of Impersonation:

1. RunWithElevatedPrivileges to impersonate as System Account user

2. Passing User Token inside SPSite to impersonate as particular user

3. Using Windows API

Note: System Account (SHAREPOINT\system) is the application pool user of SharePoint. If you are using Developer Installations on client operating systems (Windows 7 / Vista) the account name will be different.

Now let us see how to use the above methods.

1. RunWithElevatedPrivileges

This is the most commonly used method to impersonate.

SPSecurity.RunWithElevatedPrivileges(() =>

{

// Your code here

});

Note: In the case of RunWithElevatedPrivileges the System Account is used to perform the activity.

2. Passing User Token

SPUserToken is the server model which we use for the purpose. Each user’s token can be represented by this class. The User Token is actually a byte array.

The SPUser class contains the property named UserToken. Passing SPUserToken instance into the SPSite constructor impersonates the particular user.

Eg: new SPSite(UrlText.Text, user.UserToken);

For enumerating all the users of a site the web.Users property can be used.

Eg: web.Users


Running the Code

The attached source contains the following samples:

1. Enumerate Users

For enumerating users for given website the following code can be used:

using (SPSite site = new SPSite(UrlText.Text))

{

using (SPWeb web = site.OpenWeb())

{

SPContext context = SPContext.GetContext(web);

var users = context.Web.Users;

// Display to grid

usersGrid.DataSource = users.Cast<SPUser>().ToList<SPUser>();

}

}

On clicking the button we can see the following users as shown below:

– Please note that there are only 2 users for the site I use

– The current user logged in is Admin

image

2. Create Data Impersonating each User

Now we can try creating list items impersonating each user. The created item will be having the system property > Created By set to different users:

Following code performs the same:

int count = 1;

foreach (SPUser user in web.Users)

{

SPSite newSite = new SPSite(UrlText.Text, user.UserToken); // Impersonate

SPWeb newWeb = newSite.OpenWeb();

SPListItem item = newWeb.Lists[ListName].AddItem();

item[“Title”] = “Item ” + count++.ToString();

item.Update();

newSite.Dispose();

newWeb.Dispose();

}

On running the code above we can see the items created as shown below:

– Please note that the Created By property is different for each row

image

Note: An exception will be thrown if any of the user above do not have write permission.

3. Create Data using RunWithElevatedPrivileges

Now we can try creating the list items using RunWithElevatedPrivileges block. In this case the user is impersonated to System Account.

The code for the same is shown below:

SPSecurity.RunWithElevatedPrivileges(() =>

{

using (SPSite site = new SPSite(UrlText.Text))

{

using (SPWeb web = site.OpenWeb())

{

SPListItem item = web.Lists[ListName].AddItem();

item[“Title”] = “Item created with RunWithElevatedPriveleges”;

item.Update(); // Item will be created with System Account

ShowData(web);

}

}

});

We can see that the new item is created with System Account as shown below:

image

References

http://msdn.microsoft.com/en-us/library/aa543158.aspx

Summary

In this article we have explored 2 methods of Impersonation in SharePoint 2010. The associated code contains the example we have discussed.

Advertisements

5 Responses to “Impersonation in SharePoint 2010”

  1. Reblogged this on SharePoint Solutions and commented:
    Jean Paul has made this easy to follow and understand.

  2. Ankit said

    Hi Jean,
    I have read your article about impersonation.But i really did not get what is the use actually.can u please give an real example ?

    Secondly, Suppose I have a list called “Customer” in Site “A” so how can i access this list “customer ” in Site “B”.Note : SIte “B” doesnt have access to the list “Customer” … can u use impersonation here ? If so please tell me.

    Eagerly waiting for your reply.

    Regards,
    Ankit

    • Jean Paul said

      Hello Ankit,

      The scenario you mentioned should be a good example for Impersonation.

      Thank You very much for the information – From a new person’s perspective the article fails to give clarity. I will update the article with a scenario.

      Regards,
      Jean Paul

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