I am using Blazor Authentication and I scaffolded the Logon Page. I wish to redirect on the Layout page to it when the user is not authenticated, but onfortunately it does not work.
Here is my code:
[Inject] private NavigationManager nav { get; set; }
protected override async Task OnInitializedAsync()
{
var authState = await auth.GetAuthenticationStateAsync();
var user = authState.User;
if (!user.Identity.IsAuthenticated)
{
nav.NavigateTo("/Identity/Account/Login");
}
}
What is actually happening is that Blazor think the page does not exist and renders the NotFound: <p>Sorry, there's nothing at this address.</p>.
That said; without doing anything else, when I refresh the page it actually opens the login page. This does not make sense to me.
Can anyone kindly help me to understand what is happening here.
Regards,
Chris
CodePudding user response:
You should use the authorize page attribute. If you add it to the page, the blazor framework will redirect to the login page.
Is it a Blazor WASM app?
CodePudding user response:
This line of code: nav.NavigateTo("/Identity/Account/Login");
should be: nav.NavigateTo("/Identity/Account/Login", true);
Note: the url "/Identity/Account/Login"
is not within the SPA space of your Blazor application, which is why the Blazor Router cannot find it.
When you add a second parameter whose value is true
, you indicate to Blazor that you want to navigate outside of your application's space borders, as for instance:
nav.NavigateTo("https://github.com/dotnet/aspnetcore", true);
Would you please accept this answer if it helped you...