Tuesday, June 9, 2009

The right way to SPWeb.EnsureUser in SharePoint

By Hristo Yankov

At some point of time you may need to call (SPWeb).EnsureUser from your custom SharePoint web application. But this method can not be called by everyone, as it requires some high level permissions. You may also get an error similar to this one:



Your solution is to wrap the EnsureUser within RunWithElevatedPrivileges call. However, there is a big catch. If you use instances of SPSite or SPWeb, obtained prior to the RunWithElevatedPrivileges block, it won't work as expected because they are already associated to a non-elevated security context.

To illustrate it with code, here is WRONG usage of RunWithElevatedPrivileges:
SPWeb web = [... somehow obtained here...];

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// NOTE: Wrong, do not use
SPUser someUser = web.EnsureUser(web.CurrentUser.LoginName);
});

And here is a CORRECT one:
SPWeb web = [... somehow obtained here...];

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite elevatedSite = new SPSite(web.Site.ID))
{
SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
SPUser someUser = elevatedWeb.EnsureUser(web.CurrentUser.LoginName);
}
});

Basically we used the IDs of the Web and Site objects, obtained prior to the elevated block, and used them to create Site and Web object within the elevated context.
Bookmark and Share

3 comments:

The Lost Thought said...

Great stuff man, I wasted almost 3 hours just because I was expecting to get the eleviation working wihout getting a new reference.

Many thanks

Anonymous said...

Good post.Really informative

S├ębastien Sougnez said...

Hello,

thanks for this post. But don't forget to release the reference to elevatedWeb ;-)