blazorblazor-webassemblyasp.net-core-9.0

Blazor 9 WASM Logout throws AntiforgeryValidationException


I created a straight-from-the-template Blazor 9 WASM Web App with Authentication type set to Individual Accounts, and Global Webassembly interaction.

The only change I made was to swap in Microsoft.EntityFrameworkCore.InMemory.

When I run the app, I can register and log in fine.

However, when I hit the "Logout" link, it navigates to "Account/Logout" which has the following exception:

AntiforgeryValidationException: The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken".

BadHttpRequestException: Invalid anti-forgery token found when reading parameter "string returnUrl" from the request body as form.

Does anyone know what the issue is?


Solution

  • For a workaround, I added a controller:

    [Authorize]
    [Route("api/[controller]")]
    public class ManageAccountController
    {
        [HttpPost("[action]")]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
            return Ok();
        }
    }
    

    Then in my Blazor component:

    @inject HttpClient client_;
    
    <button @onclick="logout" class="btn btn-link m-0 p-0">
        Log out
    </button>
    
    @code {
        async Task logout()
        {
            var response = await client_.PostAsync("api/ManageAccount/Logout", null);
            if (response.IsSuccessStatusCode)
            {
                nav_.NavigateTo("/", forceLoad: true);
            }
        }
    }
    

    It works. Not sure why we'd need an `AntiforgeryToken` on a logout method, hopefully I'm not missing something important.