Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using django CSRF middleware with views returning JsonResponse

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.

like image 644
The Dead Mayan Avatar asked Feb 16 '18 10:02

The Dead Mayan


People also ask

Why CSRF token is not working Django?

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() .

Where should I put CSRF token Django?

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.

How does CSRF work in Django?

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.


3 Answers

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

like image 61
Gabriel Samain Avatar answered Nov 15 '22 09:11

Gabriel Samain


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"]}
like image 31
Emil Lundberg Avatar answered Nov 15 '22 07:11

Emil Lundberg


django.middleware.csrf.get_token(request)

ok then this will do what you need

like image 41
Exprator Avatar answered Nov 15 '22 07:11

Exprator