Django CSRF保护,即使我未提供csrf令牌也能给出200好的响应

时间:2020-05-06 23:32:51

标签: django csrf django-csrf

未在模板中提供{%csrf_token%},但http响应为200 ok,不应该禁止403吗?!

setting.py

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

url.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path("formtest", view.formPostTest),
]

模板formPostTest.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form class="" action="/formtest" method="post">
            <label for="username">username: </label><input type="text" name="username" value="">
            <label for="password">password: </label><input type="password" name="password" value="">
            <input type="submit" name="submit" value="submit">
        </form>
    </body>
</html>

view.py

def formPostTest(request):
    if request.method == "GET":
        cont = {}
        return render(request, "formPostTest.html", cont)
    elif request.method == "POST":
        return HttpResponse("done")

不仅如此 我厌倦了做所有事情来错过它,我篡改了csrftoken cookie the documentation

无论如何,它都会给出200 ok的响应 它给控制台带来的唯一问题

控制台

Forbidden (CSRF cookie not set.): /formtest
Forbidden (CSRF cookie not set.): /formtest
[07/May/2020 02:21:07] "POST /formtest HTTP/1.1" 200 4

有时候是这样

Forbidden (CSRF token missing or incorrect.): /formtest
[07/May/2020 02:28:44] "POST /formtest HTTP/1.1" 200 4

Django 2.0.5版 Python 3.6.5版

编辑(08/05/2020):

在探究了Django源代码之后,我发现了几件事:

  1. CsrfViewMiddleware(负责csrf保护)从不提高PermissionDenied(禁止403)。我该如何改变这种行为?

  2. 未设置csrf令牌cookie时,打印控制台错误/警告Forbidden (CSRF cookie not set.)(原因通常是处理POST的视图与发送POST的视图不同,这由装饰器{{1}解决) })

  3. 当csrf令牌cookie和csrfmiddlewaretoken无盐密码不匹配时,将显示控制台错误/警告ensure_csrf_cookie(我找不到原因,但是添加了Forbidden (CSRF token missing or incorrect.)设置了一些解决了。​​

0 个答案:

没有答案