A simple code impersonation in Sharepoint
12/12/2011 Leave a comment
Hello Everyone,
In this article i share with you a sample function that provide us code impersonation.For example you have login to sharepoint as system account and what to add an item to a custom list but you impersonate it by another user. As you know SPSecurity.RunWithElevatedPrivileges can provide us to run code as Sharepoint\system account.
So what if you impersonate with another user. The main key point is SPSite object constructor has parameter as SPUserToken, if you pass this token to the constructor,
it provide execute code with related user rights as defined with SPUserToken. For a real code impersonation you should better to use some native dll references (AdvApi32 DLL) . but this is also work for simple operations well.
Here the RunAsAdmin static class that contains ImpersonateRun fuction getting 2 parameters .
1) Account : the account to use rights
2) RunWithAdminDelegate : which is a delegate that provide us writing less codding for our implementations using lambda functions
- public static class RunAsAdmin
- {
- public delegate void RunWithAdminDelegate(SPSite site, SPWeb web);
- public static void ImpersonateRun(string account,RunWithAdminDelegate myDelegate)
- {
- Guid webID = SPContext.Current.Web.ID;
- Guid siteID = SPContext.Current.Site.ID;
- SPUser privilegedAccount =null ;
- if(string.IsNullOrEmpty(account))
- {
- privilegedAccount = SPContext.Current.Web.CurrentUser;
- }
- else
- {
- privilegedAccount = SPContext.Current.Web.EnsureUser(account);
- }
- SPUserToken privilegedToken = privilegedAccount.UserToken;
- using (SPSite site = new SPSite(siteID, privilegedToken))
- {
- site.AllowUnsafeUpdates = true;
- using (SPWeb web = site.OpenWeb(webID))
- {
- //SPWebApplication webApp = web.Site.WebApplication;
- // webApp.FormDigestSettings.Enabled = false;
- web.AllowUnsafeUpdates = true;
- myDelegate.Invoke(site, web);
- web.AllowUnsafeUpdates = false; ;
- // webApp.FormDigestSettings.Enabled = true;
- }
- }
- }
- }
the usage is very simple , Less coded less simple .
- protected void Page_Load(object sender, EventArgs e)
- {
- RunAsAdmin.ImpersonateRun(“BLOG\\bpostaci”, (site, web) =>
- {
- SPList list = web.Lists[“MyList”];
- foreach (SPListItem item in list.Items)
- {
- //Add Some items.
- }
- });
- }
see you next time.