Impersonation in MOSS 2007

At the SharePoint Conference in Berlin, Patrick Tisseghem gave a talk about the MOSS 2007 object model and the one thing that caught my eye was the new options available for doing impersonation.

Working with impersonation can be a pain and sometimes you feel like you're cheating if you have to resort to impersonation. If you've ever worked with impersonation in SPS 2003, I'm sure you know what I mean!

In MOSS 2007 you can use user tokens instead of doing old-fashioned impersonation. This opens up a number of possibilities which I will discuss in detail in a future post .

Along the same lines, MOSS 2007 allows you to easily check if a user has permission to carry out a certain task (or a series of tasks) without having to resort to trickery with try/catch blocks etc. Using the DoesUserHavePermission method on the site with the users login name returns true if the user has sufficient privileges to execute the code. Here's an example:

If(site.DoesUserHavePermission(SPContext.Current,Web.CurrentUser.Loginname, SPBsePermissions)
{
       // Do stuff here
}

Please forgive me if the above code isn't spot on, as I've yet to try it out myself. Still, it looks extremely usable and I will certainly be exploring this subject more in the weeks to come.

Lastly, I'll mention a new way of executing code with admin privileges. A simple SPSecurity.RunWithElevatedPriviliges() let's you briefly delegate admin rights to a user. This saves you doing normal impersonation of an administrator and it definitely makes your code more generic and manageable.

Leave a Reply