I'm having some issues inserting the {"X-CSRFTOKEN": client.cookies['ccsrftoken']} properly to my HTTP request.
The idea is to use the X-CSRFTOKEN for authentication on my firewall.
Here is my code:
#!/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)
On my firewall this will result with those three errors:
[httpsd 160 - 1502297425 error] is_valid_csrf_token[3015] -- CSRF token mismatch
[httpsd 160 - 1502297425 error] api_cmdb_execute_handler[1422] -- no valid CSRF token found
[httpsd 160 - 1502297425 error] api_return_http_result[528] -- API error 403 raised
Using Wireshark and comparisons with CURL commands (which works fine), I can see that the values inserted in the "X-CSRFTOKEN" is having a double-double quote. For example the output of 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+'})
Whereas this value should simply be inserted without a second "set of quote".
Any idea how to correct this?
Many thanks
here is the output of client.cookies from a new sess:
<<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//>]>
I found the solution for this.
It simply needed a string slice.
If a = client.cookies['ccsrftoken'] then csrftoken = a[1:-1]
This works fine after testing.