2012-11-26 80 views
31

如何通過python模塊請求傳遞csrftoken?這是我有什麼,但它不工作,我不知道哪個參數,將其傳遞到(數據,標題,AUTH ...)用python傳遞csrftoken請求

import requests 
from bs4 import BeautifulSoup 

URL = 'https://portal.bitcasa.com/login' 

client = requests.session(config={'verbose': sys.stderr}) 

# Retrieve the CSRF token first 
soup = BeautifulSoup(client.get('https://portal.bitcasa.com/login').content) 
csrftoken = soup.find('input', dict(name='csrfmiddlewaretoken'))['value'] 

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken) 
r = client.post(URL, data=login_data, headers={"Referer": "foo"}) 

同樣的錯誤每次消息。

<h1>Forbidden <span>(403)</span></h1> 
<p>CSRF verification failed. Request aborted.</p> 
+0

'r.text'返回什麼? 「CSRF驗證失敗」?我看到該表單還有一個'next'字段(默認爲'/'),可能需要添加?手動進行檢查時,請仔細檢查發佈的內容。 –

+0

@MartijnPieters yes CSRF驗證失敗。請求中止。「 – Jeff

+0

手動執行此操作,我看到下一個字段也是/。 – Jeff

回答

49

您需要引薦設置爲相同的URL作爲登錄頁面:

import sys 
import requests 

URL = 'https://portal.bitcasa.com/login' 

client = requests.session() 

# Retrieve the CSRF token first 
client.get(URL) # sets cookie 
if 'csrftoken' in client.cookies: 
    # Django 1.6 and up 
    csrftoken = client.cookies['csrftoken'] 
else: 
    # older versions 
    csrftoken = client.cookies['csrf'] 

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken, next='/') 
r = client.post(URL, data=login_data, headers=dict(Referer=URL)) 
1

同樣,使用Django的的csrf_client 筆記的主要區別是在使用csrftoken.value login_data。用Django測試1.10.5 -

import sys 

import django 
from django.middleware.csrf import CsrfViewMiddleware, get_token 
from django.test import Client 

django.setup() 
csrf_client = Client(enforce_csrf_checks=True) 

URL = 'http://127.0.0.1/auth/login' 
EMAIL= '[email protected]' 
PASSWORD= 'XXXX' 

# Retrieve the CSRF token first 
csrf_client.get(URL) # sets cookie 
csrftoken = csrf_client.cookies['csrftoken'] 

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken.value, next='/') 
r = csrf_client.post(URL, data=login_data, headers=dict(Referer=URL))