Inspired by: How to protect against CSRF by default in ASP.NET MVC 4?
Is there a way to achieve the same result in ASP.NET Core?
You can apply AutoValidateAntiforgeryTokenAttribute
as a global filter in Startup.ConfigureServices()
, so it applies to all of your routes automatically:
services.AddMvc(options =>
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
Note that AutoValidateAntiforgeryTokenAttribute
only applies to unsafe requests (POST, PUT), not safe ones (GET, HEAD, OPTIONS, TRACE). This way, the antiforgery token is only required for actions that are susceptible to CSRF attacks. It's important to make sure only your POST or PUT actions modify data!
This global filter approach is recommend by the official docs for non-API applications.