Passing csrftoken with python Requests

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

How do you pass a csrftoken with the python module Requests? This is what I have but it's not working, and I'm not sure which parameter to pass it into (data, headers, auth...)

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

Same error message every time.

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

回答1:

You need to set the referrer to the same URL as the login page:

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


回答2:

Similarly, using django's csrf_client note the primary difference is using csrftoken.value in the login_data. Tested with 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= 'test-user@test.com' 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))


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!