Setting the principal

If the application has the custom authentication logic implemented, then we must set the principal in two places:

  • Thread.CurrentPrincipal is the standard way to set the thread's principal in .NET.
  • HttpContext.Current.User is specific to ASP.NET.

The following code shows setting up the principal:

private void SetPrincipal(IPrincipal principal)
{
    Thread.CurrentPrincipal = principal;
    if (HttpContext.Current != null)
    {
        HttpContext.Current.User = principal;
    }
}

Get ASP.NET Web API Security Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.