Anonymous access and SPContext

Recently I was working on a public facing SharePoint publishing portal and was using SPContext to retrieve the page layout name by making a call to PublishingPage.GetPublishingPage and giving it SPContext.Current.File.Item as it’s argument.

PublishingPage page = PublishingPage.GetPublishingPage(SPContext.Current.File.Item);

Since this is a public facing web site we are using Forms based authentication and anonymous access.

What I found was that if you were accessing the web site using windows authentication that everything worked fine, but when you tried accessing the page on the fba side and were using a anonymous account, the page would throw an exception.

So after doing some debugging and with some assistance from Dennis Bottjer. We determined that accessing some of the properties from SPContext anonymously  were causing a security exception.

So to solve this problem we opted to use SPSecurity.RunWithElevatedPrivileges, here's how we did it

First we created a new SPWeb object with this line of code.

SPWeb webSite = SPContext.Current.Web;

Then inside of SPSecurity.RunWithElevatedPrivileges we created a new SPSite object using the url of the SPWeb that we created outside of the RunWithElevatedPrivileges.

SPSite siteCollection = new SPSite(webSite.Site.Url);

Once we did this, everything started working correctly, here is the entire code snippet.

SPWeb webSite = SPContext.Current.Web;

relativeUrl = SPContext.Current.Web.ServerRelativeUrl.ToString();

pageGuid = SPContext.Current.File.UniqueId;

SPSecurity.RunWithElevatedPrivileges(delegate()

{

   SPSite siteCollection = new SPSite(webSite.Site.Url);

   SPWeb webSiteHigh = siteCollection.OpenWeb(relativeUrl);

   PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(webSiteHigh);

   SPList pagesList = webSiteHigh.Lists["Pages"];

   SPListItem page = pagesList.Items[pageGuid];

   PublishingPage pubPage = PublishingPage.GetPublishingPage(page);

});

 

So the key point to remember is that if you are using SPContext on a public facing portal it may require that you run some of your code with Elevated Security Privileges.

1 Comment

Comments have been disabled for this content.