About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Wednesday, 11 December 2013

How to implement Impersonation in Sharepoint 2010

Sometime during SharePoint application development when you need your code to perform certain functions that the current user does not have the necessary permissions to perform. The SharePoint SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user. 

You need to wrap the RunWithElevatedPrivileges method around your code. And if you are working with Web forms, you may also need to set the AllowUnsafeUpdates property of SPWeb object to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowUnsafeUpdates property back to false to avoid any potential security risks.

Code example :

SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
// Get references to the site collection and site for the current context.
   // using statement makes sures these references are disposed properly.
   using (SPSite siteCollection = new objSite(mySite.ID))
      using (SPWeb web = siteCollection.OpenWeb(objWeb.ID))
         web.AllowUnsafeUpdates = true;
            //Your code
         web.AllowUnsafeUpdates = false;
         siteCollection = null;
         web = null;

No comments:

Post a Comment