0

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();
        });
xr280xr
  • 12,621
  • 7
  • 81
  • 125
  • 1
    This is pointless way of using `RunWithElevatedPrivileges` - you need to create new SPSite/SPWeb objects inside for the same siteId/webId as outer one to actually "run with elevated privileges". Fix that and see if you still have a problem. – Alexei Levenkov Oct 08 '12 at 21:04

1 Answers1

0

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!

xr280xr
  • 12,621
  • 7
  • 81
  • 125