I want to use CSRF middleware with API Views in Django. Here is a demo view I want to use CSRF with, I am confused how to integrate CSRF here.
def login(request):
try:
if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1:
print(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))
return JsonResponse({'exit':'0','msg':'Success'})
return JsonResponse({'exit':'2','msg':'User Invalid'})
except Exception as e:
return JsonResponse({'exit':'10','msg':'Unknown Error Occured'})
Any help or suggestions will be appreciated. Thanks.
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie() .
The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.
Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.
You can get the token with django.middleware.csrf.get_token(request)
And then set it in the header of the requests made client-side https://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request
To set the cookie in the response, use the @ensure_csrf_cookie
decorator:
from django.views.decorators.csrf import ensure_csrf_cookie
@require_http_methods(["GET"])
@ensure_csrf_cookie
def list_things(request):
return JsonResponse({
"things": ["foo", "bar"],
})
$ curl -i http://localhost:8000/api/v1/things
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Cookie
Set-Cookie: csrftoken=nm4SdMB0pobkQ1ab7wZTFdwMlX8wr0vfT4iAg6Nqpcatl7ITRi9VOHrKf0Krbp2i; expires=Thu, 05 Mar 2020 15:25:53 GMT; Max-Age=31449600; Path=/; SameSite=Lax
{"things": ["foo", "bar"]}
django.middleware.csrf.get_token(request)
ok then this will do what you need
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With