【问题标题】:csrf token in html, but cookie can not be sethtml中的csrf令牌,但无法设置cookie
【发布时间】:2014-10-01 18:03:13
【问题描述】:

首先我去localhost:8000看到如下页面:

</div>        

< form id="SignUpForm"  name="form_signupform"  method="post" action="hello/" > 

{% csrf_token %}  
< fieldset class="roundedCorners"  style = "display: table;"  >
< legend align="center"><em>Sign Up</em></legend>
< p></p>
< p style="display: block;">

etc.

在 localhost:8000 上面的页面视图是使用views.py中的函数提供的:

def login(request):  
    c = {}  
    c = {'query': 'abcd.com'}  
    response = render_to_response('index.html', c,context_instance=RequestContext(request))  
    return response   

在这里,在提供的页面源中,我可以看到如下 csrf 值:

< form  id="SignUpForm"  name="form_signupform"  method="post" action="hello/" >
< input type='hidden' name='csrfmiddlewaretoken'      
value='rjbU4k8DY3EEBWVhlsgIYU3gEu4x3ctM' / >   
< fieldset class="roundedCorners"  style = "display: table;" >
< legend align="center"><em>Sign Up</em></legend>
< p >< /p >
< p style="display: block;"> 

etc.

按下提交按钮时会调用另一个视图。在views.py:

def hello(request):  
    if request.method == "POST":  
        return HttpResponseRedirect("genResp1.html")  
    else:  
        return HttpResponseRedirect("genResp2.html")  

但是,在按下提交按钮时,我收到以下错误:

Forbidden (403)
    CSRF verification failed. Request aborted.
...
...
Help
Reason given for failure:
    CSRF cookie not set.

:: 我已经咨询过 a) django docs,b) stackoverflow.com,c) google 等。我已经尝试了所有可能的代码排列组合......但错误从未改变......(我可以设置cookie 调用 set_cookie 函数...可以正常工作...但是无法设置 csrf cookie...为什么?)请不要搜索网络并编写解决方案。我已经搜索了过去 6 天。我尝试了所有形式的视图功能。其中之一在上面给出。如果您自己完成了 CSRF 工作并让它运行,那么请写下您是如何做到的......(我使用 python 3.4 和 django 1.7)

【问题讨论】:

  • 在发出POST 请求时,您是否也在发送 csrf 令牌?
  • 我不明白你的解决方案......我认为它足以使用请求竞赛......你能帮我写几行代码吗?
  • 嗯,你指出的是使用 javascript 和 ajax ......但我想知道使用 html5 和内置 django 函数的解决方案......你知道如何将该令牌发送回重定向表单?
  • 使用开发者工具可以检查浏览器是否设置了csrf cookie或cookie被禁用。

标签: python django


【解决方案1】:

问题通过将CSRF_COOKIE_SECURE 设置为False 得到解决,因为我没有在我的开发机器上使用HTTPS:

  1. 修改了文件settings.py,其中包含以下行:

    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_SECURE = True
    
  2. 改成:

    CSRF_COOKIE_SECURE = False
    SESSION_COOKIE_SECURE = False
    

【讨论】:

    【解决方案2】:

    好的...我发现上面是正确的...但是在设置中我写了以下...

    # CSRF_COOKIE_NAME = 'csrfmiddlewaretoken' 
    # CSRF_COOKIE_DOMAIN = 'localhost:8000' # your domain name 
    # CSRF_COOKIE_SECURE = False 
    # CSRF_COOKIE_HTTPONLY = False 
    # CSRF_COOKIE_AGE = None 
    # CSRF_COOKIE_USED = True 
    # CSRF_COOKIE_PATH = 'C:\\Users\\me\\Desktop\\cookFol' 
    

    SESSION_EXPIRE_AT_BROWSER_CLOSE = 真

    ...看到我注释掉了那些并且它起作用了... 上面的代码都是一样的,可能是那些设置自定义有什么不匹配...

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 2021-03-10
      • 2016-06-22
      • 2019-12-24
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 2017-06-12
      • 2014-10-09
      相关资源
      最近更新 更多