I use Blazor web app with interactive Server in .NET 9.
Since I'm new and don't fully understand EF Core yet, I partially built my own login page instead of using the default Identity login provided by EF Core.
When trying to login, Blazor throws this error:
A valid antiforgery token was not provided with the request. Add an antiforgery token, or disable antiforgery validation for this endpoint.
First of all, it did work before, I didn't change anything in the login OR register page.
I tried anything I found to either disable the antiforgery token or just correctly use it (it doesn't make sense to use antiforgery token in a login form).
In my program.cs, I tried to disable the antiforgery cookie for my login and register page:
app.UseAuthentication();app.UseAuthorization();app.MapRazorComponents<App>() .AddInteractiveServerRenderMode();app.Use(async (context, next) => { if (context.Request.Path.StartsWithSegments("/login") || context.Request.Path.StartsWithSegments("/register")) { context.Features.Set<Microsoft.AspNetCore.Antiforgery.IAntiforgeryValidationFeature>(null!); } await next();});app.UseAntiforgery();I also tried just remove the app.UseAntiforgery();
But then I still get this error:
InvalidOperationException: Endpoint / (/) contains anti-forgery metadata, but a middleware was not found that supports anti-forgery.Configure your application startup by adding app.UseAntiforgery() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAntiforgery() must go between them. Calls to app.UseAntiforgery() must be placed after calls to app.UseAuthentication() and app.UseAuthorization().
I placed the antiforgery between them above them and under them.nothing helped.
This is my Login razor page:
@attribute [IgnoreAntiforgeryToken]@page "/login"@if (loginFailed) {<div class="alert alert-danger">@errorMessage</div>}<EditForm Model="Model" OnSubmit="Authenticate"><div><label for="email">E-Mail</label><InputText id="email" class="form-control" @bind-Value="Model.Email"></InputText></div><div class="mb-3"><label for="password">Passwort</label><InputText id="password" type="password" class="form-control" @bind-Value="Model.Password" /></div><button type="submit" class="btn btn-primary">Login</button><div class="mb-3">No Account yet?<a href="/register" class="text-primary"> Register now</a></div></EditForm>@code {....private async Task Authenticate(){ var user = await signInManager.UserManager.FindByEmailAsync(Model.Email); if (user == null) { loginFailed = true; errorMessage = "No User Found"; return; } var result = await signInManager.PasswordSignInAsync(user.UserName, Model.Password, isPersistent: false, lockoutOnFailure: false); if (result.Succeeded) { loginFailed = false; navigationManager.NavigateTo("/"); } else { loginFailed = true; errorMessage = "Password or Email are Incorrect"; }}}I don't know what possibly could be the cause (as said, it worked before).