我在向我的HTTP请求正确插入{“X-CSRFTOKEN”:client.cookies ['ccsrftoken']}时遇到了一些问题。
我的想法是使用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+'})
而这个值应该只插入而没有第二组“引用”。
知道如何纠正这个问题吗?
非常感谢
这是来自新sess的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//>]>
答案 0 :(得分:0)
我找到了解决方案。
它只需要一个字符串切片。
如果a = client.cookies ['ccsrftoken'] 然后csrftoken = a [1:-1]
测试后这很好用。