Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

ASP.NET Core Blazor App with API Controllers and POST endpoints does not work due to missing antiforgery token

$
0
0

If have a .NET 8 BlazorApp created from the corresponding VS template. In addition to the app's Blazor Components, there are also some API Controllers which are working fine for GET requests.

Startup code initially looked like this:

// ..app.UseStaticFiles();app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");app.UseAuthentication();app.UseAuthorization();app.UseAntiforgery();app.MapRazorComponents<App>()    .AddInteractiveServerRenderMode();app.MapControllers();// ..app.Run();

After I added a POST endpoint to a Controller, I receive a 400 Bad Request response when calling this endpoint with the message: A valid antiforgery token was not provided with the request. Add an antiforgery token, or disable antiforgery validationfor this endpoint.

I searched the web and found a couple of possible solutions. One was adding

[IgnoreAntiforgeryToken(Order = 2000)]

to the Controller class or the endpoint method. But Reqeust result remains the same after adding the attribute.Another promising solution was changing app.MapControllers(); to app.MapControllers().DisableAntiforgery(); which also had no effect. Also the hint to add builder.Services.AddControllers(opts => opts.Filters.Add(new IgnoreAntiforgeryTokenAttribute())); didn't change the behaviour.

When I remove app.UseAntiforgery(); the POST endpoint works. But this is not a real option.

I also got it running by requesting an antiforgery token first via HTTP-GET with utilizing IAntiforgery.

private readonly IAntiforgery antiforgery;[HttpGet]public IActionResult GetAntiForgeryToken(){    var tokenSet = antiforgery.GetTokens(HttpContext);    return Ok(tokenSet);}

But I don't want to bother my API users with this additional step since it doesn't make anything "more secure" when calling the API endpoint.

Question: How can I reliably achieve getting POST endpoints working without having to provide an antiforgery token while still having UseAntiforgery active in general? Why do the measures with the IgnoreAntiforgeryToken Attribute not work?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>