Common coding issues when working with anonymous SharePoint sites

Update Oct 4, 2012:
Added the usage of UnsecuredLayoutsPageBase class.

Working with anonymous SharePoint sites can be tricky sometimes. If you’re not careful, your customization codes (Web parts, custom controls, custom pages, etc.) can popup the login dialog box to anonymous users. As anonymous users they don’t have a user account, so obviously they won’t be able to enter their user ID and password. Or it simply produces an error page that either way, prevents anonymous users from accessing your site.

This post addresses some common coding issues when you work with anonymous SharePoint sites, so you can avoid it earlier.

1. Determining whether the current user is an anonymous user

How to check whether the current user is an anonymous user? I may have overlooked it, but as far as I know there is no built-in API methods for this purpose. Fortunately it’s very easy and terse. You can test the value of SPContext.Current.Web.CurrentUser. If it is null then it is accessed by an anonymous user. Here is a sample code:

if (SPContext.Current.Web.CurrentUser == null)
{
	// Anonymous user section
}
else
{
	// Authenticated user section
}

2. Beware when using SPWeb.CurrentUser

As described on the previous point, when an anonymous user is accessing a Site, the value of SPContext.Current.Web.CurrentUser will always be null. Double-check whenever you are using the property. Always make sure that you have checked for the null value, or you will end up getting the nasty “System.NullReferenceException – Object reference not set to an instance of an object.” exception.

3. Anonymous user does not have a user profile

It is an obvious yet easily overlooked one. It is a common practice to utilize the UserProfile API to store user’s personalization. Since an anonymous user does not have a user profile, provide another mean to store his/her personalization data. It could be SharePoint lists, database tables, files, or even browser cookies.

4. Working with the Publishing Feature API

I’m referring to the API under the Microsoft.SharePoint.Publishing assembly and namespace. I haven’t checked all of the API members, but not all will work with anonymous users. For example, the PublishingWeb.IsPublishingWeb(SPWeb web) works, but the PublishingWeb.GetPublishingWeb(SPWeb web) doesn’t. In fact, it will prompt the anonymous user to login by entering the user ID and password. The workaround is get an elevated SPWeb instance that has the System Account’s credential and then use the GetPublishingWeb() method on that instance. The following snippet illustrates it:

var currentWeb = SPContext.Curent.Web;
 
// the method is available to anonymous users
if (PublishingWeb.IsPublishingWeb(currentWeb))
{
	SPSecurity.RunWithElevatedPrivileges(delegate()
	{
		using (var site = new SPSite(curentWeb.Url))
		{
			using (var web = site.OpenWeb())
			{
				// the method is not available to anonymous users
				var pubWeb = PublishingWeb.GetPublishingWeb(web);
 
				// Do something with pubWeb
			}
		}
	});
}

5. Creating a custom page layout.

Your custom page layout has to inherit from the UnsecuredLayoutsPageBase class if you want to allow anonymous users to access the page, and inherit the LayoutsPageBase class if the page layout is intended only for authenticated users.

I will update this post when I find more things related to anonymous SharePoint sites. Please leave a comment if you have something to contribute, too.

  • sunny

    Hi,

    your article helped in solving my errors…Thanks !
    Keep up the good work

  • SSP

    Hi,

    Am always getting SPContext.Current.Web.CurrentUser=null when I login using forms authentication or windows wuthentication.

    any ideas why this is happening, am using Claims mode

    • http://www.denniland.com/ Denni Gautama

      Hi,

      It seems that the user object has not been added to the SharePoint site. If you know the user’s login name, you can use the SPWeb.EnsureUser method to add them to the site.

      More information about this method:
      http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.ensureuser.aspx

      • SSP

        Hi Denni,

        When the FBA user is created we are doing the SPWeb.EnsureUser. Any suggestions where else do i need to do the same? Or are you saying I need to do the same after the user is authenticated?

        Rgds,

        • http://www.denniland.com/ Denni Gautama

          Normally you only need to do it once per site collection.
          Do you get the valid value if you call HttpContext.Current.Identity?

          • SSP

            Nope i get null when i check for HttpContext.Current.Identity regardless of windows login or fba login.

          • http://www.denniland.com/ Denni Gautama

            It means that the user hasn’t been authenticated properly and is still treated as an anonymous user. Try to verify whether your authentication mechanism works properly, i.e., by checking the Sign Out button on the top of the page, or work with some out-of-the-box document libraries (upload/edit files).

          • SSP

            Hi Dennis,

            I believe the authentication mechanism is working fine because, the SignOut feature is present and is working properly. The strange thing is that when I check for SPContext.Current.Web.CurrentUser for some custom webparts (in a separate subsite) it works fine, while in the same session when it doesnt work for other webparts (in root site).

            I tried comparing the Anonymous access permission b/w the subsite and the root site, but they look the same.
            rgds