2012-11-26 15 views
31

Come si passa un csrftoken al modulo python Richieste? Questo è ciò che ho, ma non funziona, e non sono sicuro che il parametro da passare in (dati, intestazioni, auth ...)Passaggio di csrftoken con python Richieste

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"}) 

messaggio di errore stesso ogni volta.

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

Cosa restituisce 'r.text'? Ancora 'La verifica CSRF fallita'? Vedo che il modulo ha anche un campo 'next' (predefinito a'/'), forse che deve essere aggiunto? Scegli due volte cosa viene pubblicato quando lo fai manualmente. –

+0

@MartijnPieters si 'Verifica CSRF fallita. Richiesta interrotta. – Jeff

+0

Facendolo manualmente, vedo che anche il campo successivo è /. – Jeff

risposta

49

è necessario impostare il referrer per lo stesso URL, la pagina di accesso:

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

Allo stesso modo, utilizzando csrf_client nota Django 's la differenza principale sta usando csrftoken.value in il login_data. Testato con 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)) 
Problemi correlati