使用python请求和csrftoken登录

2024-10-01 09:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python的requests模块尝试登录一个网页。我打开一个请求.会话(),然后我得到cookie和包含在meta标记中的csrf令牌。我使用用户名、密码、一个隐藏的输入字段和meta标记中的csrf令牌来构建我的有效负载。之后,我使用post方法并传递登录url、cookie、有效负载和头。但是在那之后,我就不能访问登录页面后面的页面了。 我做错什么了?在

这是我执行登录时的请求头:

Request Headers:

:authority: www.die-staemme.de
:method: POST
:path: /page/auth
:scheme: https
accept: application/json, text/javascript, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
content-length: 50
content-type: application/x-www-form-urlencoded
cookie: cid=261197879; remember_optout=0; ref=start; 
PHPSESSID=3eb4f503f38bfda1c6f48b8f9036574a
origin: https://www.die-staemme.de
referer: https://www.die-staemme.de/
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
x-csrf-token: 3c49b84153f91578285e0dc4f22491126c3dfecdabfbf144
x-requested-with: XMLHttpRequest

这是我目前为止的代码:

^{pr2}$

Tags: https标记applicationcookiewwwde页面content
1条回答
网友
1楼 · 发布于 2024-10-01 09:41:08

值得注意的是,在使用Python请求模块时,您的请求与标准用户请求不完全相同。为了完全模拟真实的请求,从而不被任何防火墙或站点的安全措施阻止,您将需要复制所有POST参数、GET参数和最终头。在

您可以使用Burp Suite等工具拦截登录请求。复制它发送到的URL,同时复制所有POST参数,最后复制所有头。您应该使用requests.Session()函数来存储cookies。您可能还需要对主页执行初始会话GET请求,以便获取cookies,因为用户在未首先访问主页的情况下发送登录请求是不现实的。在

我希望这是有意义的,头参数可以这样传递:

import requests

headers = {
    'User-Agent': 'My User Agent (copy your real one for a realistic request).'
}

data = {
    'username': 'John',
    'password': 'Doe'
}

s = requests.Session()
s.get("https://mywebsite.com/")
s.post("https://mywebsite.com/", data=data, headers=headers)

相关问题 更多 >