Blazor redirect to login if user is not authenticated

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:

@inject NavigationManager NavigationManager
@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

Leave a Comment