簡體   English   中英

Django - CSRF驗證失敗

[英]Django - CSRF verification failed

嘗試從教程中創建一個簡單的表單時,我收到CSRF驗證失敗消息。 我對CSRF驗證實際上做了一些研究,據我所知,為了使用它你需要在你的html中使用其中一個csrf_token標簽,但我沒有

這是我的模板:

<form action="/testapp1/contact/" method="post">
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

相當簡單,位於contact.html

這是我的urlconf:來自django.conf.urls.defaults import *

urlpatterns=patterns('testapp1.views',
    (r'^$', 'index'),
    (r'^contact/$','contact')
)

應用名稱為testapp1。 當我輸入我的網址(http:// localhost:8000 / testapp1 / contact)時,我正確地轉到表單。 然后,當我提交表單時,我收到驗證錯誤。

這是我的觀點,雖然我不認為它是相關的:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            cc_myself = form.cleaned_data['cc_myself']
            recipients = ['info@example.com']
            if cc_myself:
                recipients.append(sender)
            print 'Sending Mail:'+subject+','+message+','+sender+','+recipients
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

修復

1 在模板中的表單標記包含{% csrf_token %}

2 如果由於任何原因你在Django 1.3及更高版本上使用render_to_response ,則用render函數替換它。 替換這個:

# Don't use this on Django 1.3 and above
return render_to_response('contact.html', {'form': form})

有了這個:

return render(request, 'contact.html', {form: form})

render函數是在Django 1.3版本中引入的 - 如果您使用的是1.2或更低版本的古老版本,則必須使用帶有RequestContext render_to_response

# Deprecated since version 2.0
return render_to_response('contact.html', {'form': form},
                   context_instance=RequestContext(request))

什么是CSRF保護,為什么我需要它?

這是一種攻擊,敵人可以強迫你的用戶做一些令人討厭的事情,如轉移資金,更改他們的電子郵件地址等等:

跨站點請求偽造(CSRF)是一種攻擊,它強制最終用戶在當前對其進行身份驗證的Web應用程序上執行不需要的操作。 CSRF攻擊專門針對狀態更改請求,而不是數據被盜,因為攻擊者無法查看對偽造請求的響應。 通過社交工程的一些幫助(例如通過電子郵件或聊天發送鏈接),攻擊者可以欺騙Web應用程序的用戶執行攻擊者選擇的操作。 如果受害者是普通用戶,則成功的CSRF攻擊可以強制用戶執行狀態更改請求,例如轉移資金,更改其電子郵件地址等。 如果受害者是管理帳戶,CSRF可能會危及整個Web應用程序。 來源: 開放Web應用程序安全項目

即使您現在不關心這類事情,應用程序也可能會增長,因此最佳做法是保持CSRF保護。

CSRF保護不應該是可選的嗎?

它是可選的,但默認情況下處於打開狀態(默認情況下包含CSRF中間件)。 你可以把它關掉:

  • 通過使用csrf_excempt裝飾器進行裝飾來獲取特定視圖。
  • 通過在settings.py從中間件列表中刪除CSRF中間件來獲取每個視圖

如果您在系統范圍內關閉它,可以通過使用csrf_protect裝飾器進行裝飾來為特定視圖打開它。

views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext

def my_view(request):
    return render_to_response('mytemplate.html', context_instance=RequestContext(request)) 

mytemlate.html:

<form action="/someurls/" method="POST">{% csrf_token %}

對於Django 1.4

settings.py

MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
)

view.py

from django.template.defaulttags import csrf_token
from django.shortcuts import render

@csrf_token
def home(request):
    """home page"""
    return render(request,
        'template.html',
            {}
    )

template.html

<form action="">
    {% csrf_token %}
....
</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM