Check user backoffice session from frontend view?

In previous versions of Umbraco, I could check the current backoffice sign-in state, to restrict access to certain (parts of) Views only for administrators. Ideally I would want to check the specific user and whether they have access to a node in the backoffice, but even a boolean “backoffice signed in or not” would suffice. With the new backoffice, I don’t see how this can be done. I know that more powerful features for extending the backoffice have been added, but I feel more comfortable adding things to a normal view right now.

I don’t appear to be the first person with this issue: How do i determine if a backoffice user is logged in from a razor view? - #3

Any help would be much appreciated!

Hi,

This method seems to work - a bit more work than you might want.

Basically create the service BackofficeUserAccessor

I found a small mistake in the interface - the return should be ClaimsIdentity.

public interface IBackofficeUserAccessor
{
  ClaimsIdentity BackofficeUser { get; }
}

Ensure you’ve registered this in your Program.cs

Then just inject into your view:

@using Umbraco.Cms.Core.Security
@using Umbraco.Cms.Web.Common.PublishedModels;
@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage
@inject UmbracoScratchpad.IBackofficeUserAccessor _backofficeUserAccessor
@{
Layout = “layout.cshtml”;

var currentUser = _backofficeUserAccessor.BackofficeUser;

}
@if(currentUser != null)
{
Hi there - @(currentUser.GetUserName())
}
else
{
You’re not logged into the CMS!
}

HTH

Steve

1 Like

Dear Steve - this is exactly what I needed.

Thank you very much!

1 Like

You’re very welcome - and welcome to the forum.

I think the real credit should go to Shekhar :laughing:

Hi all :waving_hand:

I strongly advise against using the core auth in any frontend related work. There is no guarantee it will continue to work over time, as it is strictly only intended (and maintained) for backoffice access.

I wrote a blog post about this back in February, outlining an alternative and more robust solution to this challenge. You’ll find it right here: https://kjac.dev/posts/using-umb_ucontext-with-umbraco-14-plus/

2 Likes