为什么在已经插入模板时获得“CSRF 令牌丢失”?

Why getting the "CSRF token is missing" when is already plugged in template?

提问人:Ecem 提问时间:9/19/2023 更新时间:9/19/2023 访问量:32

问:

我想使用 JQuery 通过 AJAX Post 请求发布登录表单:

即使我发送了 csrf 令牌和其他令牌,但不知何故,Django 无法使用 cookie 中的令牌进行验证。

$(function(){
    $(document).on('submit', 'form', function(event){
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'login',
            data: JSON.stringify({
                username: $('input[name=username]').val(),
                password: $('input[name=password]').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            }),
            success: function(response){
                console.log(response);
            }
           
        });
    });

以下是 url 转到的视图函数:

def login(request):
        if request.method == "POST":
            username = request.POST["username"]
            password = request.POST["password"]
            user = auth.authenticate(username=username, password=password)
            if user:
                auth.login(request, user)
                return HttpResponse("Successfully logged in!")
        
            else:
                return HttpResponse("Username or Password is incorrect")
        
        else:
            return render(request, "login.html")

1.我认为如果我不使用 {% csrf_token %} 就会解决,并且我尝试获取令牌并发送到 view.py 中的模板中呈现:

from django.middleware.csrf import get_token 
csrf_token = get_token(request)
return render(request, 'login.html', {'csrf_token':csrf_token}

它没有解决问题,我仍然遇到那个错误。

2.我认为它可能与 csrf cookie 值有关。每次我向数据库注册用户时,sessionid cookie 的值都会更改,而 csrf cookie 保持不变,但我不知道该怎么做。

任何帮助将不胜感激!

python django ajax 表单 cookie

评论

0赞 Daviid 9/19/2023
发布完整错误。发布 和 的配置值the CSRF_USE_SESSIONSCSRF_COOKIE_HTTPONLY

答:

0赞 Darsh Modi 9/19/2023 #1

在 django 模板中,表单标签中应该有一个名为 {% csrf_token %}模板标签来传递csrf_token。例如

<form method="post">
    {% csrf_token %} // this is mandatory for POST requests.
    // other tags 
    <input type="text" name='text' />
    <button type="submit">Submit</button>
</form>

完成此操作后,您可以这样做: https://stackoverflow.com/a/45490899/12098337