What is @csrf_exempt in Django?
Asked Answered
A

4

36

What is @csrf_exempt, and why should we use this in our views.py? Also, are there any alternatives to it?

Alveta answered 6/8, 2018 at 14:39 Comment(0)
R
34

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.

Raising answered 6/8, 2018 at 14:51 Comment(0)
N
14

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')
Neocene answered 6/8, 2018 at 14:50 Comment(0)
L
4

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.

Luthuli answered 21/2, 2021 at 19:33 Comment(0)
K
0

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']
Korman answered 28/1 at 9:2 Comment(1)
If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From ReviewAmber

© 2022 - 2024 — McMap. All rights reserved.