Montag, 15. März 2010

Access Denied when using EnsureUser

Sometimes you may need to call spweb.EnsureUser from your custom SharePoint web application. This method edits the user permissions on the site and needs some high level permissions like the site collection admin has.
If the user is a "Contributor" or "Reader", he will get the standard sharepoint "Error: Access Denied" message. Your EnsureUser API call has to be wrapped within RunWithElevatedPrivileges. But 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.
In the RunWithElevatedPrivileges code block you have to create a new SPSite object simply with the GUID that you get from the previously obtained site.ID.

1 Kommentar:

  1. Hello!
    Very nice article. I worked with EnsureUser a lot and 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!

    AntwortenLöschen