禁止(403)CSRF验证失败。请求中止。即使使用{%csrf_token%}

时间:2022-09-07 19:35:22

i am trying to do a login in django but i get this error, i check the CSRF documentation and nothing works for me.

我正在尝试登录django,但我收到此错误,我检查CSRF文档,没有任何对我有用。

Here is the HTML:

这是HTML:

<body>
  <section class="container">
    <div class="login">
      <h1>Login to Web App</h1>

      {% if form.errors %}
        <p class="error">Lo sentimos, la combinacion de usuario y contrasena no es correcta!</p>
      {% endif %}  

      <form action="/accounts/auth/" method="post">
      {% csrf_token %}  
      <input type='hidden' name='csrfmiddlewaretoken' value='randomchars'/>

        <p><input name="username" type="text" name="login" value="" placeholder="Username"></p>

        <p><input name="password" type="password" name="password" value="" placeholder="Password"></p>

        <p class="submit"><input type="submit" name="commit" value="Login"></p>
      </form>
    </div>
</body>

Like you see above i use the {% csrf_token %} and i have 'django.middleware.csrf.CsrfViewMiddleware' in my installed apps.

就像你在上面看到的那样,我使用了{%csrf_token%},并且在我安装的应用程序中有'django.middleware.csrf.CsrfViewMiddleware'。

And my views are:

我的观点是:

from django.http import HttpResponse,HttpResponseRedirect
from django.template.loader import get_template 
from django.template import Context
from datetime import datetime
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf

from models import *
from django.shortcuts import get_object_or_404
from forms import *
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login

def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)    


def auth_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        auth.login(request.user)
        return HttpResponse('/accounts/loggedin') 
    else:
        return HttpResponse('/accounts/invalid')

i redirect to an other HTML file where i dont use the {% csrf_token %}.

我重定向到另一个HTML文件,我不使用{%csrf_token%}。

3 个解决方案

#1


19  

Theory


A couple of things are required to make the csrf protection work (check out the docs):

要使csrf保护工作,需要做几件事(查看文档):

  1. Your browser has to accept cookies from your server
  2. 您的浏览器必须接受来自您服务器的cookie
  3. Make sure you have 'django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect)
  4. 确保你的settings.py中包含'django.middleware.csrf.CsrfViewMiddleware'作为中间件(或者在想要保护的特定视图上使用装饰器csrf_protect())
  5. Make sure you pass on the csrf token from django.core.context_processors.csrf to the context manager.
  6. 确保将django.core.context_processors.csrf中的csrf标记传递给上下文管理器。

When you load your page, have a look in the page source using your favorite browser. Don't open the template html file, open the url which point to the view containing the form. Look at where you placed the {% csrf_token %}. If you see something like

加载页面时,请使用您喜欢的浏览器查看页面源代码。不要打开模板html文件,打开指向包含表单的视图的url。看看你放置{%csrf_token%}的位置。如果你看到类似的东西

<input type='hidden' name='csrfmiddlewaretoken' value="jdwjwjefjwdjqwølksqøwkop2j3ofje" />

you should be ok.

你应该没事。

If you on the other hand see NOTPROVIDED, something has gone wrong while creating the csrf token. By looking in the source code (context_processors.py and csrf.py), we can find out what:

另一方面,如果您看到NOTPROVIDED,则在创建csrf令牌时出现问题。通过查看源代码(context_processors.py和csrf.py),我们可以找到:

  • csrf(request) returns {'csrf_token': 'NOTPROVIDED'} if get_token(request) returns None.
  • 如果get_token(request)返回None,则csrf(request)返回{'csrf_token':'NOTPROVIDED'}。
  • get_token(request) returns request.META.get("CSRF_COOKIE", None).
  • get_token(request)返回request.META.get(“CSRF_COOKIE”,无)。

I assume this means that it would return None if the cookie isn't successfully created.

我认为这意味着如果没有成功创建cookie,它将返回None。

Fix


For you, this means that you should first replace

对你而言,这意味着你应该先替换

<form action="/accounts/auth/" method="post" {% csrf_token %}>

with

<form action="/accounts/auth/" method="post">
{% csrf_token %}
(...)
</form>

We'd like the csrf field to be inside <form>...</form>, not inside <form>. As the code is at the moment, it will be converted to

我们希望csrf字段位于

... 内,而不是中。由于代码目前正在转换为

<form action="/accounts/auth/" method="post" <input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />>

and we would rather like

我们宁愿喜欢

<form action="/accounts/auth/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />

After that - have a look at the source code, and see if you can find the csrf field. If you can see it, everything should work in theory.

之后 - 查看源代码,看看是否可以找到csrf字段。如果你能看到它,一切都应该在理论上有效。

You can also check that the csrf cookie has been set in your browser, e.g. in Chrome, right-click the web page, and select Insepect Element. Select the Resources tab, and click on cookies. You should find a cookie name csrftoken there.

您还可以检查是否已在浏览器中设置了csrf cookie,例如在Chrome中,右键单击该网页,然后选择“Insepect Element”。选择“资源”选项卡,然后单击cookie。你应该在那里找到一个cookie名称csrftoken。

If you still have problems, double-check the middleware tuple in your settings.py and double-check that your browser accept cookier from your server as described above.

如果仍有问题,请仔细检查settings.py中的中间件元组,并仔细检查您的浏览器是否接受来自服务器的cookier,如上所述。

#2


0  

Clear your browser cache and try again. Maybe it is using the CSRF token saved in cookie.

清除浏览器缓存,然后重试。也许它正在使用cookie中保存的CSRF令牌。

#3


-3  

With Addition of above answer, Try Adding following lines in the views

添加上述答案后,请尝试在视图中添加以下行

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def somathing():
   return something

#1


19  

Theory


A couple of things are required to make the csrf protection work (check out the docs):

要使csrf保护工作,需要做几件事(查看文档):

  1. Your browser has to accept cookies from your server
  2. 您的浏览器必须接受来自您服务器的cookie
  3. Make sure you have 'django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect)
  4. 确保你的settings.py中包含'django.middleware.csrf.CsrfViewMiddleware'作为中间件(或者在想要保护的特定视图上使用装饰器csrf_protect())
  5. Make sure you pass on the csrf token from django.core.context_processors.csrf to the context manager.
  6. 确保将django.core.context_processors.csrf中的csrf标记传递给上下文管理器。

When you load your page, have a look in the page source using your favorite browser. Don't open the template html file, open the url which point to the view containing the form. Look at where you placed the {% csrf_token %}. If you see something like

加载页面时,请使用您喜欢的浏览器查看页面源代码。不要打开模板html文件,打开指向包含表单的视图的url。看看你放置{%csrf_token%}的位置。如果你看到类似的东西

<input type='hidden' name='csrfmiddlewaretoken' value="jdwjwjefjwdjqwølksqøwkop2j3ofje" />

you should be ok.

你应该没事。

If you on the other hand see NOTPROVIDED, something has gone wrong while creating the csrf token. By looking in the source code (context_processors.py and csrf.py), we can find out what:

另一方面,如果您看到NOTPROVIDED,则在创建csrf令牌时出现问题。通过查看源代码(context_processors.py和csrf.py),我们可以找到:

  • csrf(request) returns {'csrf_token': 'NOTPROVIDED'} if get_token(request) returns None.
  • 如果get_token(request)返回None,则csrf(request)返回{'csrf_token':'NOTPROVIDED'}。
  • get_token(request) returns request.META.get("CSRF_COOKIE", None).
  • get_token(request)返回request.META.get(“CSRF_COOKIE”,无)。

I assume this means that it would return None if the cookie isn't successfully created.

我认为这意味着如果没有成功创建cookie,它将返回None。

Fix


For you, this means that you should first replace

对你而言,这意味着你应该先替换

<form action="/accounts/auth/" method="post" {% csrf_token %}>

with

<form action="/accounts/auth/" method="post">
{% csrf_token %}
(...)
</form>

We'd like the csrf field to be inside <form>...</form>, not inside <form>. As the code is at the moment, it will be converted to

我们希望csrf字段位于

... 内,而不是中。由于代码目前正在转换为

<form action="/accounts/auth/" method="post" <input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />>

and we would rather like

我们宁愿喜欢

<form action="/accounts/auth/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='randomchars' />

After that - have a look at the source code, and see if you can find the csrf field. If you can see it, everything should work in theory.

之后 - 查看源代码,看看是否可以找到csrf字段。如果你能看到它,一切都应该在理论上有效。

You can also check that the csrf cookie has been set in your browser, e.g. in Chrome, right-click the web page, and select Insepect Element. Select the Resources tab, and click on cookies. You should find a cookie name csrftoken there.

您还可以检查是否已在浏览器中设置了csrf cookie,例如在Chrome中,右键单击该网页,然后选择“Insepect Element”。选择“资源”选项卡,然后单击cookie。你应该在那里找到一个cookie名称csrftoken。

If you still have problems, double-check the middleware tuple in your settings.py and double-check that your browser accept cookier from your server as described above.

如果仍有问题,请仔细检查settings.py中的中间件元组,并仔细检查您的浏览器是否接受来自服务器的cookier,如上所述。

#2


0  

Clear your browser cache and try again. Maybe it is using the CSRF token saved in cookie.

清除浏览器缓存,然后重试。也许它正在使用cookie中保存的CSRF令牌。

#3


-3  

With Addition of above answer, Try Adding following lines in the views

添加上述答案后,请尝试在视图中添加以下行

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def somathing():
   return something