使用Python请求库向DVWA发布请求时缺少CSRF令牌

2024-10-06 12:27:20 发布

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

我正在尝试做一个程序,将允许我提交一个网站上的用户名和密码。为此,我使用的是运行在localhost:8080上的DVWA(该死的易受攻击的Web应用程序) 但每当我尝试发送post请求时,它总是返回一个错误

csrf token is incorrect

这是我的密码:

import requests
url = 'http://192.168.43.1:8080/login.php'
data_dict = {"username": "admin", "password": "password", "Login": "Login"}
response = requests.post(url, data_dict)
print(response.text)

Tags: 程序weblocalhosturl密码data网站response
1条回答
网友
1楼 · 发布于 2024-10-06 12:27:20

您需要首先对该URL发出GET请求,并从响应中解析正确的“CSRF”值(在本例中为user_token)。从响应HTML中,您可以找到隐藏值:

<input type="hidden" name="user_token" value="28e01134ddf00ec2ea4ce48bcaf0fc55">

另外,您似乎需要将第一个GET请求中的cookie包含在下一个请求中——这可以通过使用request.Session()对象自动完成。您可以通过第一个响应中的print(resp.cookies)来查看cookie

下面是修改后的代码。我正在使用BeautifulSoup库解析html—它找到正确的输入字段,并从中获取值

POST方法随后在user_token参数中使用此值

from bs4 import BeautifulSoup
import requests

with requests.Session() as s:

    url = 'http://192.168.43.1:8080/login.php'
    resp = s.get(url)
    parsed_html = BeautifulSoup(resp.content, features="html.parser")
    input_value = parsed_html.body.find('input', attrs={'name':'user_token'}).get("value")
    data_dict = {"username": "admin", "password": "password", "Login": "Login", "user_token":input_value}
    response = s.post(url, data_dict)
    print(response.content)

相关问题 更多 >