Z
Z
zlodiak2019-06-25 17:28:14
Django
zlodiak, 2019-06-25 17:28:14

How to exchange csrf token with frontend?

There is a frontend in angular and a backend in django2.2.2. The frontend consists of one page, which has a registration form. I would like to sign it with a csrf token, send it and check for the presence of a token on the server side.
Here is what I tried to do to implement this
view idea:

from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie


@ensure_csrf_cookie
def get_csrf(request):
    response = JsonResponse([{"cookie_set": True}], safe=False)
    return response

def registration(request):
    # some payload
    response = JsonResponse([{"registration_successful": True}], safe=False)
    return response

On the frontend, when loading a page with a form, I send a request, to which the get_csrf () controller responds. Here, in my opinion, the csrf token in the form of cookies should return to the front.
then when submitting the form, I could extract the cookie from the client and send it along with the rest of the POST parameters to the registration () controller. In the absence of it, the controller simply will not process the form data.
The problem is that the cookie is not set after the first page load on the front. And I don’t understand why, because if you drive the browser into the address bar:
127.0.0.1:8000/app_auth/get_csrf

, then the cookie is set.
Please tell me what am I doing wrong and where should I go. Just please do not offer high-level solutions because I would like to understand the mechanism in general

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question