Open ddony8128 opened 2 years ago
I guess you meant to say @ensure_csrf_cookie
instead of @ensure_csrf_token
?
I haven't quite understood how you came to realize there is no security check at all when you've tried tagging with @ensure_csrf_cookie
on every function. I might be able to give you more concrete help if you elaborate more. To clarify facts with csrf_token, it is the CSRF middleware that provides CSRF protection. If you have a look at MIDDLEWARE list at settings.py, you'll see django.middleware.csrf.CsrfViewMiddleware
and this is the middleware that checks whether request from client includes valid CSRF token. So as long as you have the csrf middleware, your project is protected by CSRF check all the time, except for some view functions that are decorated with @csrf_exempt
. Meanwhile, @ensure_csrf_cookie
is in charge of setting the cookie with CSRF token. This document provides step-by-step explanation on how CSRF protection works in Django so I recommend you to have a look.
Of course it is not the only appropriate way and you may apply whatever other method that better suits your project.
While developing our project, I need to treat CSRF token, but it's a little confusing.
As I know, @csrf_exempt tag in django just doesn't bother CSRF and @ensure_csrf_token tag first doesn't checks CSRF for the request and then set the client's cookie with a CSRF token.
We didn't want to request 'GET /api/token/' for every arbitrary connection for every page, so I've tried tagging @ensure_csrf_token on every single function in views.py. But soon I have realized it means that there is no security check at all. @ensure_csrf_token doesn't checks CSRF.
I'm curious if what I know about CSRF is right. And also curious that tagging @ensure_csrf_token just on /api/token and requesting GET /api/token/ is the only appropriate way.