【问题标题】:Django 403 CSRF Verification FailedDjango 403 CSRF 验证失败
【发布时间】:2017-03-29 16:56:34
【问题描述】:

我正在为我的学校编写一个招生网站,并使用 Django 作为框架。对于注册,我需要用户名、密码和注册令牌。这些还有待验证,我现在要做的就是从注册输入页面(使用 POST 请求)转到“您已成功注册”页面。在某个地方,csrf 令牌显然拒绝被验证。

我的看法:

def register(request):
    return render(request, 'enroller/successfulEnroll.html')

我的页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="{% url 'register' %}" method="post"> {% csrf_token %}
    <div class="container">
        <label><b>New Username</b></label>
        <input type="text" placeholder="Username" name="uname" required>
        <br>
        <label><b>Password</b></label>
        <input type="password" placeholder="Password" name="psw" required>
        <br>
        <label><b>Registration Password</b></label>
        <input type="text" placeholder="Registration Key" name="reg" required>
        <br>
        <input type="submit" value="Register" />
    </div>
    </form>
</body>
</html>

当我尝试从注册页面转到成功页面时,它给了我一个错误 403(CSRF 验证失败。请求中止)。但是,当我尝试访问 url mysite.com/register/ 时,它会返回我请求的页面而没有错误。

有没有办法解决这个问题?我一直在研究 RequestContext,但我不完全确定它会在哪里使用。

【问题讨论】:

  • csrf 上的 1.10 文档提到您正在使用的渲染函数(假设它是导入的 django 渲染)应该涵盖 RequestContext。到目前为止,您显示的代码看起来不错。这可能是中间件设置、站点设置中的另一个问题,但不是您发布的看起来不错的代码。顺便说一句,当您使用浏览器直接访问 GET 请求的 url 时,CSRF 并不真正相关。可能值得考虑在成功处理表单后使用单独的成功视图并执行 HttpResponseRedirect。

标签: python django csrf


【解决方案1】:

让它工作。丹尼尔是对的——这是我的中间件配置的问题。我在 settings.py 中的中间件数组之前添加了两行,突然间它起作用了。

SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

我不能说我完全确定它为什么起作用,或者问题到底是什么,但它现在起作用了。谢谢丹尼尔!

【讨论】:

  • 问题可能是会话过旧并且已过期,但没有被新会话替换。当我删除浏览器中的 cookie 时,403 问题就消失了。您的第二个变量是指此会话清除。但是,请注意,现在您的用户在关闭浏览器时都会注销。
【解决方案2】:

也许你可以使用这个方法。而djang版本是1.11.1

from django.shortcuts import render
from django.template.context_processors import csrf

form = LoginForm()
c = {'form': form}
c.update(csrf(request))
return render(request, 'a_template.html', c)

我在http://djangobook.com/security-in-django/ 找到了这个方法
对我来说,做工不错,但不是最好的,因为不止一条线。

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 2020-05-04
    • 2018-06-06
    • 2012-09-08
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多