使用 python 请求传递 csrftoken [英] Passing csrftoken with python Requests

查看:25
本文介绍了使用 python 请求传递 csrftoken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何通过 python 模块请求传递 csrftoken?这就是我所拥有的,但它不起作用,而且我不确定将其传递给哪个参数(数据、标题、身份验证...)

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>

推荐答案

如果您要设置referrer 标头,那么对于该特定站点,您需要将referrer 设置为与登录页面相同的URL:

If you are going to set the referrer header, then for that specific site 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))

当使用不安全的 http 时,Referer 标头通常会被过滤掉,否则很容易被欺骗,因此大多数站点不再需要设置标头.但是,当使用 SSL 连接并且设置了 SSL 连接时,站点验证它是否至少引用了可以在逻辑上发起请求的内容确实有意义.Django 在连接加密时执行此操作(使用 https://),然后主动要求它.

When using unsecured http, the Referer header is often filtered out and otherwise easily spoofable anyway, so most sites no longer require the header to be set. However, when using an SSL connection and if it is set, it does make sense for the site to validate that it at least references something that could logically have initiated the request. Django does this when the connection is encrypted (uses https://), and actively requires it then.

这篇关于使用 python 请求传递 csrftoken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆