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

2

6

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?

Interracial answered 15/2, 2018 at 16:10 Comment(3)
learn.microsoft.com/en-us/aspnet/core/security/…Envelop
@MU So if I were to add this globally, simply adding services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); would be enough?Interracial
@Interracial Yes, that will automatically enforce CSRF validation on all routes.Vow
V
6

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.

Vow answered 15/2, 2018 at 16:28 Comment(2)
So I don't even need to Ignore the GET's?Interracial
@Interracial With AutoValidate you don't need to use IgnoreAntiforgeryToken on GET routes. That's the "auto" part. :)Vow
P
1

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.

Powe answered 15/2, 2018 at 16:30 Comment(2)
One of the problems with tokens (in a non-API context) is storing them safely. Cookies are vulnerable to CSRF, but they at least have the HttpOnly flag. Storing stuff in localStorage doesn't have that safety measure. See this discussion: security.stackexchange.com/a/148163/110474Vow
Yes, I know, but you have to first execute something like XSS to read them. It's not like anyone can just do it, but it's of course a valid concern. Also if you have ability to read from local storage you can probably just call any webapi you want anyway, cookie will be sent automatically.Powe

© 2022 - 2024 — McMap. All rights reserved.