Let me start by saying that while executing code via RunWithElevatedPrivileges may help you overcome certain “access denied” exceptions in your code, using it should be the exception not the norm. This is not meant to be a “how to” posting on RunWithElevatedPrivileges, there are plenty of articles out there that already cover just that. Instead I’d like to focus on a subject that I consider to be just as important; when is the right (and wrong) time to use this command.
I recently wrote an article for the MSDN on “Securing Application Pages for Windows SharePoint Services 3.0”. In it, I provided several code samples on how to do just what its title implies; some of which included calls to RunWithElevatedPrivileges. A respected colleague was quick to point out a concern; that some of the information contained in the article (specifically references to RunWithElevatedPrivileges) might result in certain individuals using the command without giving it sufficient thought.
The very reason I wrote the article, stems from how often I’ve seen this command used, and the security risks it presents. I’d hate for the article to be seen as a case or excuse for calling this command, when in large part is the very thing it tries to protect developers from.
SharePoint provides a very extensive and well thought out API, at least from a security standpoint ;). It uses impersonation, meaning that the code you write will execute under the context of the user viewing the page where your code resides. If you write a web part or application page that reads or writes information from a SharePoint List, Library, or Site that does not grant the user such rights; your web part or application page will throw an error… as it should. Your first instinct should not be to rewrite your code so that this logic executes via the RunWithElevatedPrivileges command. Doing so might be considered a hack.
That’s not to say using RunWithElevatedPrivileges is a “hack” every time, there are certain unique cases where you don’t have much of a choice. But first consider checking if the user has the necessary permissions via the DoesUserHavePermission method of either the SPSite, SPWeb, SPList, or even SPListItem your accessing with your code, and avoid doing anything further on that item if the method returns false for the required permission level. Alternatively (although often cause for debate) consider handling the access denied exception. Ultimately, don’t hurry too much writing your code, the quickest way is not always the best way.
Happy Coding. Oh.. and thanks for the pointer Matt.