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:
Better
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?
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