Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check for (and send) empty body on log out post. #136

Merged
merged 2 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions 8.0/BlazorWebAssemblyStandaloneWithIdentity/Backend/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
Expand Down Expand Up @@ -42,13 +43,21 @@
app.MapIdentityApi<AppUser>();

// provide an end point to clear the cookie for logout
// NOTE: This logout code will be updated shortly.
// https://github.com/dotnet/blazor-samples/issues/132
app.MapPost("/Logout", async (ClaimsPrincipal user, SignInManager<AppUser> signInManager) =>
// The request checks for an empty body to prevent CSRF attacks. By requiring something
// in the body, the request must be made from JavaScript, which is the only way to
// access the cookie. It can't be accessed by a form-based post.
// This prevents a malicious site from logging the user out.
// Furthermore, the endpoint is protected by authorization to prevent anonymous access.
// The client simply needs to pass an empty object {} in the body of the request.
app.MapPost("/Logout", async (SignInManager<AppUser> signInManager, [FromBody] object empty) =>
{
await signInManager.SignOutAsync();
return TypedResults.Ok();
});
if (empty != null)
{
await signInManager.SignOutAsync();
return Results.Ok();
}
return Results.Unauthorized();
}).RequireAuthorization();

// activate the CORS policy
app.UseCors("wasm");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Text.Json;
using System.Net.Http.Json;
using BlazorWasmAuth.Identity.Models;
using System.Text;

namespace BlazorWasmAuth.Identity
{
Expand Down Expand Up @@ -201,7 +202,9 @@ public override async Task<AuthenticationState> GetAuthenticationStateAsync()

public async Task LogoutAsync()
{
await _httpClient.PostAsync("Logout", null);
const string Empty = "{}";
var emptyContent = new StringContent(Empty, Encoding.UTF8, "application/json");
await _httpClient.PostAsync("Logout", emptyContent);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}

Expand Down