SPListItem.Update throws UnauthorizedAccessException for Forms authenticated user

1.5k Views Asked by At

I'm trying to fix some code (that I didn't write) that inserts an item into a SharePoint list. The problem is the code works for anonymous users, but if the user is logged in via ASP.NET forms authentication, it gets an UnauthorizedAccessException when calling the Update method of the SPListItem. When it works, as an anonymous user, I can see the the SPUser of the SPListItem's SPWeb is the SharePoint system account. But when the user is logged in with Forms Authentication, the SPUser is null. Can someone explain this behavior and how to fix it?

Originally only the top block of code was in the RunWithElevatedPrivileges delegate, but I tried moving it all inside. I'll insert some using blocks once I get it working:

SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            rootWeb = SPContext.Current.Site.RootWeb;
            rootWeb.AllowUnsafeUpdates = true;
            currentWeb = SPContext.Current.Web;
            currentWeb.AllowUnsafeUpdates = true;

        try
        {
            // Get site information
            SPList franDir = rootWeb.GetList("/Lists/Directory");
            SPQuery query = new SPQuery();
            query.Query = "<Where><Eq><FieldRef Name='Subsite'/><Value Type='Text'>" + currentWeb.Name +
                 "</Value></Eq></Where>";

            SPListItemCollection items = franDir.GetItems(query);

            SPList l = rootWeb.GetList("/Lists/Request");

            SPListItem li = l.Items.Add();
            li["Location"] = siteName;
            //...set more fields


            li.Update();

        }
        catch (Exception ex)
        {
            rootWeb.Dispose();
            logger.ErrorException("An error occured adding item", ex);
            throw ex;
        }

        rootWeb.Dispose();
        });
1

There are 1 best solutions below

0
On

Thanks to @AlexeiLevenkov I see that this doesn't work because I'm using an existing instance of the SP objects which were created using the default privileges. As proof that the code does nothing, when running as an anonymous user the code succeeds even without the RunWithElevatedPrivileges call. I made this change and it took care of it.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
     rootWeb = new SPSite(SPContext.Current.Site.ID).RootWeb;

Thanks a lot!