In the previous version of Blazor I could use:
await SignOutManager.SetSignOutState();
Navigation.NavigateTo($"authentication/logout");
Now, I have to use:
Navigation.NavigateToLogout("authentication/logout");
But the following code redirects me to Not found. Should I create a page "authentication/logout" or what?
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject NavigationManager Navigation
<AuthorizeView>
<Authorized>
<button class="nav-link btn btn-link" @onclick="BeginLogOut">Log out</button>
</Authorized>
<NotAuthorized>
<a href="Account/Login">Log in</a>
</NotAuthorized>
</AuthorizeView>
@code{
private void BeginLogOut()
{
Navigation.NavigateToLogout("authentication/logout");
}
}
There is no single example anywhere :/
This worked for me (ServerSide .NET 8): 1. Create a new class in your namespace
public static class StartupExtensions
{
public static void MapAccountServices(this IEndpointRouteBuilder app)
{
app
.MapGet("/Logout", async (HttpContext context, string returnUrl = "/") =>
{
await context.SignOutAsync(IdentityConstants.ApplicationScheme);
context.Response.Redirect(returnUrl);
})
.RequireAuthorization();
}
}
Add/alter this in Program.cs
app.UseRouting();
app.UseAntiforgery();
app.UseAuthorization();
app.UseEndpoints(
endpoints =>
{
endpoints.MapAccountServices();
}
);
for .net8 blazor application I created a new component Logout.razor
.
I am redirecting to Home page however you can redirect as per your requirement.
@page "/Account/Logout"
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Identity
@inject IdentityRedirectManager RedirectManager
<PageTitle>Log Out</PageTitle>
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
protected override async Task OnInitializedAsync() {
if (HttpMethods.IsGet(HttpContext.Request.Method)) {
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);
RedirectManager.RedirectTo("/");
}
}
}
and in menu I just hit that link
<a class="btn btn-sm btn-light justify-center" href="/Account/Logout">
Log out
</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With