Thursday, August 18, 2011

Access denied even after SPSecurity.RunWithElevatedPrivileges(delegate()

There is a problem I faced and I spent quite some time trying to solve it. I had a basic query. In my code, I was trying to access the groups as below:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
_site.AllowUnsafeUpdates = true;
Web.AllowUnsafeUpdates = true;
foreach (SPGroup group in Web.Groups)
{
if (group.Name == "WFM")
{
SPUserCollection userCollection = group.Users;
foreach (SPUser users in userCollection)
{
fuv = new SPFieldUserValue(Web, users.ID, users.LoginName);
UserValue.Add(fuv);
}
}
}

Web.AllowUnsafeUpdates = false;
_site.AllowUnsafeUpdates = false ;
});


But, it was always giving me access denied error. If we are doing Runwithelevatedprivilidges, I should not get access denied error.

Trick was to take care of two things:
1. you need to initiate a SPSite object with in the SPSecurity.RunWithElevetedPrivilges.

2. Create SPSite using ID. This is most important thing.

It worked after changing the code to below:


SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb webContext = SPContext.Current.Web;
Guid newSite;

using (SPSite site = new SPSite(webContext.Site.ID))
{
using (SPWeb web = site.OpenWeb(webContext.ID))
{
....

Phew......