Thursday, March 7, 2013

Impersonation

Impersonation, a feature that was added in Windows SharePoint Services 3.0, enables you to perform actions on behalf of another user. Impersonation is useful in scenarios such as timer operations that need to update something asynchronously on behalf of a user or to run a high privilege code for a low privilege user.

You can either RunWithElevatedPrivileges to impersonate the System Account or by passing an User Token to the SPSite object to impersonate a specific user.

Note:
This is not to be used to perform long running processes as user tokens usually expire after approximately 24 hours.

RunWithElevatedPrivileges  (impersonate the System Account)
SPSecurity.RunWithElevatedPrivileges(() =>
{
   // Your code here
});

Passing User Token (impersonate a specific user)
Get site context using the system account.
Then get the user token of the user you want to impersonate.
Finally use this to open a new SPSite using this users token.

SPUserToken userToken = tmpWeb.AllUsers[someUser].UserToken;

using (SPSite site = new SPSite(url, userToken))
{
    using (SPWeb web = site.OpenWeb())
    {
         // Your code here
    }
}

Note:
Impersonation requires two-way trust and will not be available if the Web front-end that interacts with the SharePoint database sits on a server that is located between two other networks as in such scenarios the Web front-end server has only one-way trust.

No comments:

Post a Comment