Sitecore's GetActiveUser Result Isn't Always the Active One


I have been working on an effort that relies on the knowledge of the current Sitecore user when using the Content Editor. Through review of the work I was realizing that the Sitecore user I was retrieving necessarily wasn’t the individual logged in at the current time. Of course after some time debugging I found that in some scenarios, the Sitecore.Security.Authentication.AuthenticationManager.GetActiveUser() was returning the initial logged in account when the  application first started.

After a Sitecore support request I was able to get verification of what I found.

In my application, processing for certain tasks were being performed through a series of providers. These providers were run in unique threads to circumvent some potential performance bottlenecks. When the execution of these providers would take place, the Sitecore context would no longer be available during processing. This was the trigger for GetActiveUser to provide a different value than what I would have expected versus the execution of the method when the Sitecore context was available.

The puzzling part for me, is I understood with no Sitecore context, it would be natural not to get my expected result. That makes sense to me. What I was baffled about is the result was that of another account, in which I would typically expect a null or empty response to the method based on context existence.

The answer from Sitecore Support (thanks Viktor, Alexey and Michael!) is this retrieval is intended behavior. So if the HttpContext is not available the thread current principal is used for the Sitecore User result.

HttpContext current = HttpContext.Current;
  if (current == null)
  {
    if (Thread.CurrentPrincipal != null)
    {
      if (Thread.CurrentPrincipal is User)
      {
         return Thread.CurrentPrincipal as User;
      }
      if (!string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name))
      {
        return base.GetUser(Thread.CurrentPrincipal.Identity.Name, Thread.CurrentPrincipal.Identity.IsAuthenticated);
      }
    }
    return null;
  }

I’m still honestly not sure if I like the fact I get a different User Account than the one I would expect versus getting a null regardless of current principal checks, but as stated – intended behavior.

So if needing to get your active user and knowing that you will lose your HttpContext in logic processing, it might be wise to grab what you need prior to the loss of such context and carry it along in logic for processing when needed.


Tags: Sitecore;

SEARCH ARTICLES