Skip to main content

Cloud

Access Denied” / “401-UnAuthorised” error while accessing the “DefaultPage” property of Publishing Web class for anonymous access.

In our project, we were facing a weird problem while using our custom master pages on MOSS publishing portal, getting an “Access Denied” / “401-UnAuthorised” error while accessing the portal for Anonymous User Access(Internet Zone). If we apply any other default master page site works fine. Finally got the solution, just want to share the solution.

Problem :

In master page code behind we were accessing DefaultPage property of PublishingWeb class. Problem is while accessing “DefaultPage” property of PublishingWeb class in code behind of master page.

Whenever we access DefaultPage property of PublishingWeb instance from the current context it always gives either “Access Denied” or “401-UnAuthorised” error even though you execute this code in elevated privileges as

SPSecurity.RunWithElevatedPrivileges(delegate(){

PublishingPage currentPublishingPage = PublishingPage.GetPublishingPage(SPContext.Current.ListItem);

PublishingWeb currentPublishingWeb = PublishingWeb.GetPublishingWeb(SPContext.Current.Web);

if (SPContext.Current.Web.IsRootWeb && SPContext.Current.Item.ID == currentPublishingWeb.DefaultPage.Item.ID) //– Here it asks for UN and Password for anonymous access also

{

PlaceHolderPageTitle.Controls.Add(new Literal { Text = "Default Page Title" });

}

else

{

string pageTitle = currentPublishingPage.Title.Substring(0, 40 – SPContext.Current.Web.Title.Length) + "…";

PlaceHolderPageTitle.Controls.Add(new Literal { Text = SPContext.Current.Web.Title + ": " + pageTitle + " – Sample Text" });

}

});

Solution:

Get the current IDs of site collection and web and then use constructor to get the SPSite and SPWeb as

Guid siteId = SPContext.Current.Site.ID;

Guid webId = SPContext.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate(){

SPSite elevatedSite = new SPSite(siteId); // Used the constructor

SPWeb elevatedWeb = elevatedSite.OpenWeb(webId);//used constructor

PublishingWeb currentPublishingWeb = PublishingWeb.GetPublishingWeb(elevatedWeb);

PublishingPage currentPublishingPage = PublishingPage.GetPublishingPage(SPContext.Current.ListItem);

if (SPContext.Current.Web.IsRootWeb && SPContext.Current.Item.ID == currentPublishingWeb.DefaultPage.Item.ID)// Now this works fine

{

this.PlaceHolderPageTitle.Controls.Add(new Literal { Text = " Default Page Title" });

}

else

{

PlaceHolderPageTitle.Controls.Add(new Literal { Text = SPContext.Current.Web.Title + ": " + currentPublishingPage.Title + " – Sample Text " });

}

elevatedWeb.Dispose();

elevatedSite.Dispose();

});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PointBridge Blogs

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram