0

In all examples so far I saw examples how to show completely different views -- one for the case when the user is logged in, the other when the user is not logged in.

And I would like to display the same elements, just enable/disable some depending if the user is logged in or not. I though I can go with reading context.User.Identity.IsAuthenticated and use it like this:

<NavLink class="nav-link" href="foobar" 
  IsDisabled="@(!(context.User.Identity?.IsAuthenticated ?? false))">
  ...
</NavLink>

But this requires context. This property is provided by AuthorizeView and this component in turn enforces the aforementioned strict split between two sets of views.

So how to achieve just enable/disable with single common view?

I am fully aware it is not security measure of any kind.

Update Both answers work with the same effect (thank you once again), but with small caveat -- just right after logging in both methods still returns info user is not authenticated. Here is the follow-up question: How to get fresh information whether the user is logged in?

2 Answers 2

1

You can obtain the authentication state data by defining a cascading parameter of type Task<AuthenticationState>

Here's a full sample from the docs:

@page "/"

<button @onclick="LogUsername">Log username</button>

<p>@_authMessage</p>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private string _authMessage;

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            _authMessage = $"{user.Identity.Name} is authenticated.";
        }
        else
        {
            _authMessage = "The user is NOT authenticated.";
        }
    }
}

Note: The CascadingAuthenticationState component is the component that exposes the authentication state to interested parties...

1
  • Many thanks. Just for record, currently this code does not work for me as expected -- after logging in the LoginDisplay component shows I am logged id, shows my name, yet this code claims I am not authenticated. After reloading entire page it states I am -- so both parties are in sync. Now the question is why it cannot see I am logged in, after logging in (I will open another question for it). Commented Jan 20, 2021 at 6:49
1

You should be able to use the AuthenticationStateProvider for that. In the official docs there is an example how to do it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.