Friday, June 11, 2010

Access denied error when code runs with SPsecurity.RunWithElevatedPriviliges

Today, while reviewing code ,I have found some thing, which will give access denied error if our code runs with SPSecurity.RunWithElevatedPriviliges and AllowUnsafeUpdates = true

Check the piece of code which I have written below that gives access denied error

using (SPSite site = new SPSite(SPContext.Current.Web))
{
SPList list = web.Lists[listUrl];
SPFieldCollection fieldCol = list.Fields;
SPListItem newItem = list.Items.Add();
foreach (SPField field in fieldCol)
{
if (!field.Hidden && !field.ReadOnlyField)
{
if (field.Title.Equals(question, StringComparison.OrdinalIgnoreCase))
{
newItem[field.Title] = answer;
web.AllowUnsafeUpdates = true;
newItem.Update();
web.AllowUnsafeUpdates = false;
break;
}
break;
}
}
}

The main problem here is that the current request will execute under the priviligies of anonymous user credentials because user is a anonymous user, so this code always gives access denied error

The web object is created using SPContext, so this web object is runs under credentials of spcontext, so this always gives problem

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[listUrl];
SPFieldCollection fieldCol = list.Fields;
SPListItem newItem = list.Items.Add();
foreach (SPField field in fieldCol)
{
if (!field.Hidden && !field.ReadOnlyField)
{
if (field.Title.Equals(question, StringComparison.OrdinalIgnoreCase))
{
newItem[field.Title] = answer;
web.AllowUnsafeUpdates = true;
newItem.Update();
web.AllowUnsafeUpdates = false;
break;
}
break;
}
}
}
}

The above code will run under credentials of system account that means with full permissons so this will execute fine here the difference is we are creting spsite object with url not from current context and the SPsecurity.RunWithElevatedPriviges will work fine here

1 comment: