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