Blazor redirect to login if user is not authenticated

Leonardo Lurci picture Leonardo Lurci · Mar 25, 2020 · Viewed 8.7k times · Source

I am trying to develop an app using Blazor WebAssembly and I am wondering about how I can protect my whole application if the user is not authenticated. The behavior I would implement is:

  • If an anonymous user asks for any page, then he will be redirected to the login page

Better

  • a user must be authenticated for using this app

At the moment I've implemented this behavior applying the [Authorize] attribute to every page, but I would like to centralize it.

I've achieved this goal on Blazor Server Side applying the [Authorize] attribute inside the _host.razor component.

Is there a solution even for Blazor Client Side?

Answer

Brett picture Brett · Jun 11, 2020

There may be slicker ways of doing this, but this is what worked for me:

Assuming you've configured Authentication correctly according to these instructions

In your MainLayout.razor (which is used by default for all components) add a code block as follows:

@code{ 

    [CascadingParameter] protected Task<AuthenticationState> AuthStat { get; set; }

    protected async override Task OnInitializedAsync()
    {
        base.OnInitialized();
        var user = (await AuthStat).User;
        if(!user.Identity.IsAuthenticated)
        {
            NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}");
        }
    }
}

If the user is not authenticated, we redirect to the built-in The RemoteAuthenticatorView component at the "authentication/" enpoint with the "login" action. This should kick-off authentication