使用Python Requests库向DVWA发送POST请求时CSRF Token缺失问题
Hey there! The issue here is that DVWA enables CSRF protection by default for the login form (and other sensitive actions). Your current script is missing the required CSRF token embedded in the login page's HTML—you need to fetch this token first before sending your POST request.
Here's how to fix this step-by-step:
1. Understand the Root Cause
DVWA generates a unique user_token (the CSRF token) for each session and embeds it as a hidden field in the login form. When you send a POST request without this token (or with an invalid one), the server rejects the request with the "csrf token is incorrect" error.
2. Modified Script with CSRF Token Handling
We'll use requests.Session() to maintain cookies across requests (critical for keeping your session alive) and parse the login page to extract the token. We'll use BeautifulSoup for easy HTML parsing—install it first with pip install beautifulsoup4.
import requests from bs4 import BeautifulSoup # Initialize a session to persist cookies session = requests.Session() # DVWA login URL login_url = 'http://192.168.43.1:8080/login.php' # Step 1: Fetch the login page to get the CSRF token response = session.get(login_url) soup = BeautifulSoup(response.text, 'html.parser') # Extract the user_token from the hidden input field user_token = soup.find('input', {'name': 'user_token'}).get('value') # Step 2: Prepare login data with the extracted token login_data = { 'username': 'admin', 'password': 'password', 'user_token': user_token, 'Login': 'Login' } # Step 3: Send the POST request with the correct token response = session.post(login_url, data=login_data) # Check if login was successful if 'Welcome to Damn Vulnerable Web Application!' in response.text: print("Login successful!") else: print("Login failed. Response content:") print(response.text)
3. Key Notes
- Session Persistence: Using
requests.Session()ensures that cookies (like PHPSESSID) are kept between the GET and POST requests, which DVWA needs to recognize your session. - Token Extraction: The
user_tokenlives in a hidden<input>field withname="user_token"—we use BeautifulSoup to locate this field and grab its dynamic value. - DVWA Security Level: If you still hit issues, check your DVWA security level. Lower levels may have looser CSRF rules, but testing with default settings mimics real-world scenarios best.
内容的提问来源于stack exchange,提问作者Faiyaz Ahmad

