Search This Blog

Monday, March 14, 2011

Access Denied error while using SPWeb.EnsureUser in SharePoint

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 like this:

----------------------------------------
Error: Access Denied

Current User
You are currently signed in as: DOMAIN\USER

Sign in as different user
Request access
-----------------------------------------

Solution:

The solution for this is to wrap the EnsureUser within RunWithElevatedPrivileges call. However, there is a big catch.

NOTE: 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 = SPContext.Current.Web;

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

});


And here is a CORRECT one:
SPWeb web = SPContext.Current.Web;

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.



5 comments:

  1. Hi
    I have written the code as you said.. I have assigned a Roledefinition for the user and to an Item in the list.. However, I have executed program fine. I have assigned "Contribute" permissions for the user to edit an Item.
    When I tried to edit, Edit form is opened but while updating the item I am getting the same error.

    Please help me..

    ReplyDelete
  2. Can you please share your exact code Pandu.

    ReplyDelete
  3. Thank you Nitin.. It is resolved...

    ReplyDelete
  4. Hello!
    Very nice article. I worked with EnsureUser a lot and found out that if user doesn't exist in user collection, it will be tried to add to this collection, but this means that spWeb object will be modified and it's required AllowUnsafeUpdates = true. Eventually, I've developed a small method-wrapper for EnsureUser. It's shown in my blog - http://dotnetfollower.com/wordpress/2011/05/sharepoint-wrapper-over-ensureuser/
    Thanks!

    ReplyDelete
  5. I try with given delegate but same issue

    Error: Access Denied

    Current User
    You are currently signed in as: DOMAIN\USER

    Sign in as different user
    Request access


    but when i refresh url then gives permission for user so what should i do for this issue i need to refresh url for each time

    ReplyDelete