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.
Another way to protect from CSRF for good is not using cookies for authentication at all. If that is a possibility I would try checking token authentication and implement it. No cookie, no CSRF.
As far as I know it's not a big deal to have JWT token auth e.g. with Core.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With