Login

How do I save a page as an anonymous user?

Versions: 4.70, FAQ number: 104, Old FAQ number: 943

Q: How do I save a page as anonymous user?

A: First, create a new EPiServer user account that acts as an anonymous user and give account appropriate rights. Second, write your code so that it acts as the anonymous user, no matter who the real current user is. 

The sample below shows how to create and save a new page as the anonymous user. 

// The code uses the following EPiServer namespaces
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAccess;
using EPiServer.Security;

// Save current user account so we can restore it later
UnifiedPrincipal originalUser = CurrentUser;

PageData page;

// Get user named "WebAnonymous" with password "123"
IPrincipal principal =
  AuthenticationProvider.Authenticate(this, "WebAnonymous", "123");

// Switch to anonymous user. Everything that is done from
// now on is done using the anonymous account.
CurrentUser = principal as UnifiedPrincipal;

// Create a new page
PageReference parent = Global.EPConfig.StartPage;
int pageTypeID = 4;
page = Global.EPDataFactory.GetDefaultPageData(parent, pageTypeID);
page.PageName = "Page created by " + CurrentUser.Identity.Name;

Global.EPDataFactory.Save(page, SaveAction.Publish);

// Page created and saved and we are done.
// If we want to continue doing things in the current request 
// as the real user, we need to revert back to the user we
// saved earlier.
CurrentUser = originalUser;
EPiTrace logger