Impersonation in Sharepoint (RunWithElevatedPrivileges)
Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.The 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.
The premise is that you wrap the RunWithElevatedPrivileges method around your code. And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.
Code example
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
// The using statement makes sures these references are disposed properly.
using (SPSite siteCollection = new SPSite(mySite.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
web.AllowUnsafeUpdates = true;
try
{
//Your code
}
web.AllowUnsafeUpdates = false;
//siteCollection = null;
//web = null;
}
No comments:
Post a Comment