Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect against CSRF by default in ASP.NET Core

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?

like image 701
Ludisposed Avatar asked Feb 15 '18 16:02

Ludisposed


2 Answers

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.

like image 71
Nate Barbettini Avatar answered Nov 01 '22 14:11

Nate Barbettini


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.

like image 25
Ilya Chernomordik Avatar answered Nov 01 '22 12:11

Ilya Chernomordik