I have the following Python code. I'm trying to send some data to a SAP system. I have opened a session, how do I get the csrf-token value from the session? I've tried looking for it using client.cookies['csrftoken']
but it throws up an error, possibly because the CSRF token isn't there or if I'm not using the correct key name to get the CSRF token value.
Earlier, I've tried without opening a session with a simple get request, and am able to get the CSRF token value, but I suppose the token doesn't hold, and found that a session is needed to maintain the token value.
Printing print client.cookies
just gives <RequestsCookieJar[<Cookie sap-usercontext=sap-client=100 for 34.239.8.24/>]>
, and printing print.client.headers
gives {'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.9.1'}
. How do I find the CSRF token from here?
URL = "https://34.239.8.24:44300/sap/opu/odata/sap/ZRECEASY_PO_GL_POST_SRV/ZRECEASY_PO_GL_POSTSet"
auth_get_po_data ='S4H_FIN','Welcome1'
data = { "BUKR": 1710,"EBELN": 4500000004, "EBELP": 10,"EINDT": "20161103","OPEN_AMT": "3,000.00","PERC_REC_AMT": 0,"REC_AMT": 0, "ITEM_AMT": "3,000.00","INV_AMT": 0,"WAERS": "USD", "UPD_BY": "","UPD_DAT": "", "INV_APP": "", "SAKTO": "null", "KOSTL": "null", "AUFNR": "", "DESC": "", "KUNNR_NAM": "", "KUNNR": "", "COMMENT": "" }
client = requests.session()
client.get(URL, verify=False)
print client.cookies
csrftoken = client.cookies['csrftoken']
print csrftoken
login_data = dict(username="S4H_FIN", password="Welcome1", csrftoken=csrftoken, next='/')
r = client.post(URL, data=data, auth=auth_get_po_data, verify=False, headers=dict(Referer=URL))
print (r.text)
Such a token can be retrieved via a previous service call to the ABAP server. For this, first on a none-changing call (GET, HEAD, OPTIONS), the client has to get this token by setting the HTTP header X-CSRF-Token to the value Fetch. A CSRF token is returned by the ABAP server in the same header and can be used for subsequent, server state changing calls using header X-CSRF-Token. (as described in the SAP Online Help) https://help.sap.com/saphelp_nw74/helpdata/de/55/74ed6c93654ee4999b4d07cdda532c/frameset.htm Best Regards, Andre