เหตุใดการตรวจสอบ CSRF การเข้าสู่ระบบนี้จึงล้มเหลว ฉันสามารถรับกุญแจได้

import requests
from bs4 import BeautifulSoup as bs
import lxml

# Page header
head= { 'Content-Type':'application/x-www-form-urlencoded',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
# Start Page
url = 'https://www.rewardstyle.com'
# Login URL
login_url = 'https://auth.rewardstyle.com/login/'
# URL behind the login page
url2= 'https://www.rewardstyle.com/products/recent?lang=en_US'


# Open up a session
s = requests.session()

# Open the login page
r = s.get(login_url)
# Retrieve the CSRF token first
csrftoken = s.cookies['csrftoken']
print(csrftoken)

สิ่งนี้จะพิมพ์โทเค็น csrf แม้ว่าข้อผิดพลาดของฉันอาจเป็นว่าไม่ถูกต้องใช่ไหม ต่อไปฉันโพสต์ข้อมูล แต่ไม่มีโชค:

# Get the page cookie
cookies = r.cookies

# Set CSRF-Token
head['X-CSRF-Token'] = csrftoken
head['X-Requested-With'] = 'XMLHttpRequest'

payload = {
'username':'myuser',
'password':'mypassword',
}

r = requests.post(login_url, data=payload, headers = head)
print(r.content)

ฉันรวมผู้ใช้และรหัสผ่านที่ถูกต้อง ข้อผิดพลาดของฉันคือ:

สิ่งต้องห้าม (403)

การตรวจสอบ CSRF ล้มเหลว คำขอถูกยกเลิก

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons


person joshgallantt    schedule 13.01.2021    source แหล่งที่มา


คำตอบ (1)


สิ่งนี้ใช้ได้กับทุกคนที่สงสัย

import requests
from bs4 import BeautifulSoup as bs
import lxml

# Page header
head= { 'Content-Type':'application/x-www-form-urlencoded',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
# Start Page
url = 'https://www.rewardstyle.com'
# Login URL
login_url = 'https://auth.rewardstyle.com/login/'
# URL behind the login page
url2= 'https://www.rewardstyle.com/products/recent?lang=en_US'


# Open up a session
s = requests.session()

# Open the login page
r = s.get(login_url)
# Retrieve the CSRF token first
csrftoken = s.cookies['csrftoken']
print(csrftoken) #Check if it's getting printed. Sometimes key name could be 'csrf' only

# Get the page cookie
cookies = r.cookies

# Set CSRF-Token
head['X-CSRF-Token'] = csrftoken
head['X-Requested-With'] = 'XMLHttpRequest'
head['Referer'] = login_url

payload = {
'username':'username',
'password':'password',
'csrfmiddlewaretoken' : csrftoken,
}

r = s.post(login_url, data=payload, headers = head)
print(r.content)

# Try to get a page behind the login page
r = s.get(url2)

# Check if login was successful
print(r.content)
person joshgallantt    schedule 13.01.2021