I wanted to provide an update for those using IOptionsSnapshot to parse the currently logged in user without receiving an authentication header in APIs - that may not work anymore in the latest versions of Umbraco. Fortunately, Umbraco now has a built-in method so you don’t have to parse the cookie anymore.
Instead of this:
public ClaimsIdentity BackofficeUser
{
get
{
var httpContext = httpContextAccessor.HttpContext;
if (httpContext == null)
return new ClaimsIdentity();
var cookieOptions = cookieOptionsSnapshot.Get(UmbConstants.Security.BackOfficeAuthenticationType);
var backOfficeCookie = httpContext.Request.Cookies[cookieOptions.Cookie.Name!];
if (string.IsNullOrEmpty(backOfficeCookie))
return new ClaimsIdentity();
var unprotected = cookieOptions.TicketDataFormat.Unprotect(backOfficeCookie!);
if (unprotected == null)
return new ClaimsIdentity();
var backOfficeIdentity = unprotected!.Principal.GetUmbracoIdentity();
return backOfficeIdentity ?? new ClaimsIdentity();
}
}
do this:
public async Task<ClaimsIdentity> GetBackofficeUserAsync()
{
var httpContext = httpContextAccessor.HttpContext;
if (httpContext == null)
return new ClaimsIdentity();
// Runs the request through the real UmbracoBackOffice cookie authentication
// handler, rather than re-deriving the ticket format by hand.
var result = await httpContext.AuthenticateBackOfficeAsync();
if (!result.Succeeded || result.Principal == null)
return new ClaimsIdentity();
return result.Principal.GetUmbracoIdentity() ?? new ClaimsIdentity();
}
There is no reason for IOptionsSnapshot references anymore.
Old thread: