What is @csrf_exempt
, and why should we use this in our views.py
? Also, are there any alternatives to it?
Normally when you make a request via a form you want the form being submitted to your view to originate from your website and not come from some other domain. To ensure that this happens, you can put a csrf token in your form for your view to recognize. If you add @csrf_exempt
to the top of your view, then you are basically telling the view that it doesn't need the token. This is a security exemption that you should take seriously.
The decorator marks a view as being exempt from the protection ensured by the middleware. Example:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
You should not have to use this unless you know exactly why. A good example where it is used is to build a webhook, that will receive informations from another site via a POST request. You then must be able to receive data even if it has no csrf token, but will be replaced by another system of security. For example, if you use stripe for the subscriptions of your clients, you need to know if a client unsubscribed his account. The webhook will be the way to inform your site, and then cut the access to your service for the unsubscribed client.
Is there any sense in this decorator if ive already adjusted csrf settings like this:
ALLOWED_HOSTS = ['*']
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000',
'http://127.0.0.1:3000',
'http://0.0.0.0:3000',
]
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = False
CSRF_TRUSTED_ORIGINS = ['http://localhost:3000', 'http://127.0.0.1:3000', 'http://0.0.0.0:3000']
© 2022 - 2024 — McMap. All rights reserved.