Tuesday, September 27, 2011

Run With Elevated Privileges



Say you have implemented a webpart in one of your sharepoint sites. This web part will be used by all types of users from admins to readers. If some part of your web part code need to execute with Full Control rights even if the user does not have Full Control, SPSecurity.RunWithElevatedPrivileges Method can be used.


The following example sends an email using elevated privileges. This will elevate the privileges to execute using the service account. The SPSecurity.RunWithElevatedPrivileges method taks a delegate method as its argument and executes that code with the service account.


public void SendEmail(Email email)
{
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
        SmtpClient mail = new SmtpClient();    MailMessage message = new MailMessage();
            message.From = new MailAddress(this.SenderAddress);
            message.To.Add(email.To);
            message.IsBodyHtml = email.IsHtml;  
            message.CC.Add(email.Cc);  
            message.Bcc.Add(email.Bcc);  
            message.ReplyTo = new MailAddress(this.ReplyToAddress);  
            message.Subject = email.Subject;  
            message.Body = email.Body;


        mail.Host = this.CentralAdminOutboundServerAddress; mail.Send(message);
    });
}


This would allow the lower users too to use the email functionality without any issues even though it uses mail settings from central admin.



Delegate method or delegated block of code being excuted within RunWithElevatedPrivileges, will be executed with privileges of System Account i.e. the App Pool identity of the respective web application.
RunWithElevatedPrivileges should be used when code should execute SharePoint API on securable objects or processes for which current user doesn't have pemissions.
If it is required to access SPSite or SPWeb object for the current site, while executing block of code within RunWithElevatedPrivileges, new context for the SPSite and SPWeb should be created.
Common mistake developers make is use of SPSite or SPWeb objects retrieved from SPContext.Current in RunWithElevatedPrivileges block. This objects will have current user permission levels on the securable objects, not of the System Account.

No comments:

Post a Comment