greenoldman
greenoldman

Reputation: 21062

How to enable/disable elements depending whether the user is logged in or not?

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?

Upvotes: 0

Views: 751

Answers (2)

enet
enet

Reputation: 45586

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...

Upvotes: 1

Zsolt Bendes
Zsolt Bendes

Reputation: 2569

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

Upvotes: 1

Related Questions