I implement authorization on a site (Python + Django) on C #. There was a question about protection against CSRF attacks (before that, all views were set by the decorator @csrf_exempt, because it is inconvenient to debug, and not up to it). Actually, there was a request handler for authentication of the form:

def AuthentificationPost(request): form = AuthentificationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(username=email, password=password) if user is None: response = u'Не верный логин или пароль.' return HttpResponse(json.dumps({'error': response, 'result': 'error'})) else: login(request, user) user.save() return HttpResponse(json.dumps({'result': 'success'})) else: errors = {} for i in form.errors: errors[i] = form.errors[i][0] return HttpResponse(json.dumps({'errors': errors, 'result': 'error'})) 

Naturally, if you immediately start logging in on the client side, the csrf check will not be passed, because the client did not receive a cookie with a token, which means there is nothing to send back to the server In manuals (official, and not so) everywhere it is chewed, as the django token transmits, but where it is not said when, and under what conditions . I realized this when I checked that HttpResponse (status = 200) does not return any cookies. Then came up with the following solution:

  def AuthentificationPost(request): if request.method == 'GET': return HttpResponse(get_token(request)) else: form = AuthentificationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(username=email, password=password) if user is None: response = u'Не верный логин или пароль.' return HttpResponse(json.dumps({'error': response, 'result': 'error'})) else: login(request, user) user.save() return HttpResponse(json.dumps({'result': 'success'})) else: errors = {} for i in form.errors: errors[i] = form.errors[i][0] return HttpResponse(json.dumps({'errors': errors, 'result': 'error'})) 

Problem solved. Now the cook is coming. But, now when you go to the authentication page in the browser, a string with a token is shown, and ideally it should be 404. Therefore, the question arises: am I doing everything correctly? Is there a kosher solution?

    1 answer 1

    The truth, as it turns out in most cases, was near. After a thorough study of English-speaking resources, it turned out that the cookie with a token is attached to the session, so there is no point in looking for it before authentication. It also says that the {% csrf_token%} template tag in the registration and authentication forms has no practical meaning.