【发布时间】:2017-08-21 21:11:03
【问题描述】:
我在将 {"X-CSRFTOKEN": client.cookies['ccsrftoken']} 正确插入我的 HTTP 请求时遇到了一些问题。
这个想法是在我的防火墙上使用 X-CSRFTOKEN 进行身份验证。
这是我的代码:
#!/usr/bin/env python
import requests
url = 'http://10.0.2.45/'
name = 'admin'
password = 'xyz'
#all cookies received will be stored in the session object
client = requests.session()
print 'client headers initially: ', client.headers, '\n'
#First connection used for authentication.
login = client.post(url + '/logincheck', data="username=" + name + "&secretkey=" + password, verify = False)
#csrftoken to be inserted in the headers for next put,post,delete requests.
This will be stored in csrftoken variable.
print 'client cookies after login: ', client.cookies, '\n \n'
print 'csrftoken value extracted from the cookie: ',
client.cookies['ccsrftoken'], '\n \n'
#we update the session headers with X-CSRFTOKEN
client.headers.update({"X-CSRFTOKEN": client.cookies['ccsrftoken']})
#Simple post command (empty, just to test authentication)
api_cmdb = 'api/v2/cmdb/'
c = client.post(url + api_cmdb + 'firewall/address?vdom=root', verify = False)
在我的防火墙上,这将导致这三个错误:
[httpsd 160 - 1502297425 错误] is_valid_csrf_token[3015] -- CSRF 令牌不匹配
[httpsd 160 - 1502297425 错误] api_cmdb_execute_handler[1422] -- 找不到有效的 CSRF 令牌
[httpsd 160 - 1502297425 错误] api_return_http_result[528] -- 引发 API 错误 403
使用 Wireshark 并与 CURL 命令进行比较(效果很好),我可以看到插入“X-CSRFTOKEN”中的值带有双引号。例如 client.headers.update({"X-CSRFTOKEN": client.cookies['ccsrftoken']}):
的输出CaseInsensitiveDict({'X-CSRFTOKEN': '"6C369B52B8211679DF2AC9676945CC"', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'python-requests/2.2.1 CPython/2.7.6 Linux/3.4.0+'})
而这个值应该被简单地插入而不需要第二个“引用集”。
知道如何纠正这个问题吗?
非常感谢
这是来自新会话的 client.cookies 的输出:
<<class 'requests.cookies.RequestsCookieJar'>
[<Cookie APSCOOKIE_9539865664988587055="Era%3D0%26Payload%3DGAytA5jioAyuHvus1rw3dfKdzWrJm3CyraiFVxenLzBRb6qHLqlcnIIUaZz5ZJma%0A7MyKPN+4hgCPi8+yGeMhLdTVAAlG0zHmtPw7y6v+nrJVc1g7NZisFowGZ4TZacfL%0AaiMjHE+0MuJLA7r6COt4G+ikwMWlh8YWO0RF5rvE0t6nYX%2FLvla1yFjKy5Odu7kA%0AeewY6sB0zbybh6eRSWQf5Q%3D%3D%0A%26AuthHash%3DLolbIaWtHofmkwMG1Fh6gWc6K%2FkA%0A"
for 10.0.2.45/>,
<Cookie ccsrftoken="2A28F281C83FF4B3235134C335D53B5" for 10.0.2.45//>,
<Cookie ccsrftoken_9539865664988587055="2A28F281C83FF4B3235134C335D53B5" for 10.0.2.45//>]>
【问题讨论】:
-
登录后打印
client.cookies的那一行的输出是什么? -
Hello @Lukas, from a new sess: [
, , 的“2A28F281C83FF4B3235134C335D53B5”]> -
不清楚哪个输出来自
client.cookies['ccsrftoken']。请相应地Edit您的问题。
标签: python cookies python-requests csrf