python - 使用 Python 请求模块登录时凭据无效
问题描述
我正在尝试通过 Pythonrequests
模块登录 Spotify。似乎无论我提供的凭据是对还是错,我总是会收到无效的凭据 JSON 错误。这是我到目前为止的代码:
import requests
import time
s = requests.Session()
print(s.cookies.get_dict())
s.get("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F")
print(s.cookies.get_dict())
print('\n')
csrftoken = s.cookies['csrf_token']
print('\n')
print(csrftoken)
req = s.post('https://accounts.spotify.com/api/login', data={'remember':'true', 'username':'VALIDUSERNAME', 'password':'VALIDPASSWORD', 'captcha_token': '', 'csrf_token':csrftoken}, headers={'Referer': 'https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:64.0) Gecko/20100101 Firefox/64.0'})
print(req.status_code)
print(req.text)
我总是收到这样的 JSON 响应:
{"error":"errorInvalidCredentials"}
我观察到将 CSRF 令牌更改为无效值时,我仍然得到{"error":"errorInvalidCredentials"}
响应。然后我使用 Burp Suite 的代理来更改令牌,我得到了不同的响应,告诉我 CSRF 令牌无效。
我还观察到验证码参数的值是什么。在 Burp 中拦截请求时,参数的值没有设置为任何值,这就是我将其留空的原因。
我究竟做错了什么?我知道我提供了有效的凭据并提供了正确的 CSRF 令牌。
解决方案
查看我的代码后,我意识到我什至没有在发送请求的同时发送一个 cookie,我只是将 CSRF 令牌作为 POST 请求参数发送。当我查看 Burp Suite 中截获的 POST 登录请求时,我终于明白我做错了什么。
实际 Spotify 登录页面的 cookie 标头是这样的:
Cookie: sp_ab=%7B%222018_12_homepage_variants%22%3A%22v4%22%2C%222018_11_invisible_captcha%22%3A%22control%22%2C%222018_09_acq_signup_confirm_email%22%3A%22control%22%2C%222018_08_acq_signup_components_update%22%3A%22control%22%7D; sp_t=767144f8aa8b61378ccf958c670a6383; _ga=GA1.2.1942983958.1544578963; _gid=GA1.2.1472574661.1544578963; spot=%7B%22t%22%3A1544579600%2C%22m%22%3A%22us%22%2C%22p%22%3A%22open%22%7D; _gcl_au=1.1.1737135149.1544579416; __gads=ID=da7551ef6408e0e1:T=1544579604:S=ALNI_Mac1_7j2-834CH4t2FY65VEg9Pfcg; csrf_token=AQDFzF3zWOZKdg3w_agEStexYetTUTDpgFhvKXLmIaqTTP9ZDn84FctVC_ZER2m_O-4Obzt3w7fL-XKDBp_CdtNzIlUwD6iEffkWOK8ojTxHwTqzlWCoRcY2tYYO4wBSPJKKug; __bon=MHwwfDE4MDkxMzU2MjV8NzU5ODM2OTYyNTB8MXwxfDF8MQ==; fb_continue=https%3A%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F; remember=test; _gat=1
因此,我所要做的就是添加一个 cookie 标头,复制并粘贴所有静态 cookie(每个会话的值总是相同的)并连接几个动态的(每个会话都不同的session) 带有变量的 cookie,例如 csrf 令牌。
推荐阅读
- sharepoint - Microsoft Graph 调用 PATCH(更新)列表项字段是否区分大小写?
- c++ - 用于数组/向量的 C++ SFINAE
- visual-studio - Intellisense 抱怨“命名空间标准没有成员 size_t”。如何消除此(错误)错误?
- javascript - 在 Django 中的 Ajax 中传递花括号数据
- java - 如何在 iText Java 中的 ColumnText 之后添加段落?
- airflow - 无法在气流 dag 中使用 python 模块
- python - 如何对最后n列进行分组和求和
- c# - UWP XAML 自定义命令栏切换按钮
- ios - WKWebView 视频播放器替换 UINavigationController
- r - 在R中添加共享相同日期的不同行的数据