Here’s a big gotcha that I came across recently – if you’re developing a public facing Sharepoint site which will be using anonymous access, check your code for any references to PublishingWeb.DefaultPage. Because direct access to the Defaultpage / home page of a Publishing Web requires the “Browse Directories” permission which isn’t part of the Limited Access role which anonymous users get by default, unauthenticated users will come across 401 Unauthorized exceptions once they hit the code that looks for the Publishing Web’s default page.
The best way to fix this is to run code that refers to the DefaultPage using SPSecurity.RunWithElevatedPrivileges() – but here’s another gotcha! You can’t use SPContext.Current.Web within RunWithElevatedPrivileges, as it will still be running under the current user’s credentials, and not the system account that you need. Therefore, you need to reopen a reference to the SPWeb/SPSite within the RunWithElevatedPrivileges call.
Some sample code follows below…
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
if (PublishingWeb.IsPublishingWeb(SPContext.Current.Web))
{
//reopen the web to get it under the elevated privileges - otherwise you can't access pweb.defaultpage
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite elevatedSite = new SPSite(site.ID))
{
using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID))
{
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(elevatedWeb);
SPItem defaultPageItem = pWeb.DefaultPage.Item;
}
}
});
}
Thank you for this, just what I was looking for.
Argh! Watch out for this on intranets as well where everyone has the visitor role. The visitor role doesn’t include the Browse permission level.
Thanks !
[...] method causes Access Denied exception for anonymous users. Alternative solutions here and here and in many other blogs. You could use SPSecurity.RunWithElevatedPrivileges, but [...]