In his comment to my latest article about impersonation in event handlers, Anders Rask said an interesting thing. He suggested that I use the "RunWithElevatedPrivileges" function of the SPSecurity class to run the piece of code as the account running the application pool.
He was kind enough to leave a code sample, and it is clear he knows what he is talking about (check out his article about impersontion in a web part for the 2003 version. Link requires registration to MSD2D.com - a site I don't believe still exists, seeing it's horrible interface).
To answer Mr. Rask, I will explain why I am not using this "simple" impersonation:
- Because I don't always want to impersonate that system account. My clients are very security sensitive, and system accounts get as little permissions as possible. If my event handler needs to do things that require access to systems that the account is not supposed to touch, we need to impersonate another account.
- Because it doesn't work!
Ok, maybe I am over reacting, but the fact of the matter is that even though the "SPSecurity.RunWithElevatedPrivileges" seems to switch to the system account, I actually get 'access denied' when I try to access resources that the account should have permissions to access.
Example: in my event handler I want to write to a log file. Because the data written to the log is very sensitive, I want to put the log file in a secure file system folder on the server. for this example, "c:\temp" is secure enough. I made the application pool account a server administrator (more, much more than you need to write a file in c:\temp) and still I get permission denied when the event handler is trying to open the stream.
Using the impersonation example of Victor Vogelpoel [Macaw] I had no problem specifying the actuall application pool account and it's password and the log file is writing!
Even more, I check the "web.CurrentUser" value and that returns "SHAREPOINT\system" and not the user name for the application pool (I guess that is why it fails accessing the file system). It also didn't "see" the document library that I had removed all user access from (except the SHAREPOINT\system and the application pool account).
So my analysis say - the "RunWithElevatedPrivileges" may be useful in webparts (I never tried), but looks to be useless in Event Handlers (at least for my purposes).
I would welcome any feedback!