How can I configure my Blazor WebAssembly to require authenticated users for the entire app rather than mark each page or controllers with the [Authorize] attribute?
You can check the authentication status on the main page's load and decide what to do next.
My app should only allow authorized users, and the recommended configuration loads a little bit of the page before redirecting to the login.
Copy code bellow to the Index.razor
@inject NavigationManager Navigation
@code{
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
protected async override Task OnInitializedAsync()
{
base.OnInitialized();
var authState = await authenticationStateTask;
var user = authState.User;
if(!user.Identity.IsAuthenticated)
{
Navigation.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(Navigation.Uri)}");
}
}
}
There is some other solutions suggesting to add @attribute [Microsoft.AspNetCore.Authorization.Authorize]
on _Imports.cs
and @attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]
on the pages which doesnt need authorization. This never worked for me as expected, but good to know about it.