Sunday, November 17, 2013

How to Allow a Virtual User to Browse on Pages with Saving Profile Values

There is an ability in Sitecore named Virtual Users. It could be used for many purposes, for example emulating of site view and work for different users. There is one limitation described in Security API Cookbook:
You must log in a virtual user only after you assign Roles and Profile properties to them. The Roles and Profile properties that are assigned after logging in are lost upon subsequent request.

This limitation make work with profiles changes useless: you could get profile values, but you couldn't change profile values. For example, saving values for virtual user on WFFM form will not work.  But this limitation could be overcame.

If Sitecore API cookbook requires login after assigning roles and profile properties, you could add your own processor to httpRequestEnd pipeline.

<httpRequestEnd>
     <processor type=" YourNamespace.Pipelines.HttpRequestEnd.LoginVirtualUser,  YourAssemblyName"
patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.EndDiagnostics, Sitecore.Kernel']" />
</httpRequestEnd>

namespace YourNamespace.Pipelines.HttpRequestEnd
{
    using Sitecore.ExperienceExplorer.Business.Helpers;
    using Sitecore.Pipelines.HttpRequest;
    using Sitecore.Security.Authentication;

    //this processor is used for applying settings to profiles of virtual users
    public class LoginVirtualUser : HttpRequestProcessor
    {
      public override void Process(HttpRequestArgs args)
      {
         if (Context.User.RuntimeSettings.IsVirtual)
         {
             AuthenticationManager.Login(Context.User);
         }
      }
    }
}

Voila, now assigning roles and changing profile properties works also for Sitecore virtual users.