I am building a simple custom authentication method in my Blazor app. The several pages must be visible by a logged-in user through the Razor <AuthorizeView> attribute.
I am able to make it work by adding to the ClaimsPrincipal (obtained through the cascading AuthenticationState) a new ClaimsIdentity with a non-null authentication type (which is the info the AuthorizeView attribute uses when no Role or Policy is specified, see Why is my ClaimsIdentity IsAuthenticated always false (for web api Authorize filter)?). But then I am not able to remove that "authenticated" ClaimsIdentity when I want to "log-out" the user.
The workaround I have found is to plug a role called "loggedin" into the principal (through a new ClaimsIdentity) when he logs in, and unplug the role from the related ClaimsIdentity when he logs out. The Razor attribute controlling the visibility is then <AuthorizeView Role="loggedin">. I could also use a Policy, but both seem dirty to me, since here I only want the pages to be visible when the user is authenticated (instead of being "authorized", which roles and policies are made for, and I find is a concept that should be distincted from mere authentication). But maybe it's the right thing to do, I don't know.
So, what is the cleanest way to specify that a page should be visible only to authenticated users (without further conditions), and control the authentication state of the user, only using the Razor AuthorizeView attribute (and children), ClaimsPrincipal and ClaimsIdentity ?
As you're question is light on code, here's a demo on how to do what I think you want. This is based on Blazor Server.
It uses a custom
AuthenticationStateProviderto capture the original user and store the claims. You can then construct your ownClaimsIdentityandClaimsPrincipalusing the captured claims. If you principals have more that one identity you will need to code to capture that.A custom authentication State Provider:
Registered:
A demo Layout to toggle the authentication.