Skip to Content
0
Dec 26, 2022 at 07:16 PM

CSRF Token Fetching for Python Client - OData Services

1504 Views

I am trying to use Python requests library to fetch the csrf token for an OData service using GET request (code stub below). However the response header doesnt have any flag corresponding to csrf token value.

This would subsequently be used for doing a POST on one of the tables but the token validation fails.

I tried using Postman and it successfully generates csrf token in response header.

OUTPUT:

Cookies xx.de/>, xx.de/>]>

Response Header

{'set-cookie': 'sap-usercontext=sap-client=3xx; path=/, SAP_SESSIONID_xx_3xx=VdUUsfqf19sYMFW3jmRDLWajmUWFSRHtttlFfWVfZdw%3d; path=/; HttpOnly', 'content-type': 'application/xml', 'content-length': '889', 'dataserviceversion': '1.0', 'sap-server': 'true', 'sap-perf-fesrec': '74990.000000'}

Session Header

{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

import requests
import json
url="http://url/sap/opu/odata/sap/Service/EntitySet/$format=xml"

sess = requests.session()
sess.headers.update({'Connection': 'keep-alive'})
params= { 'x-csrf-token': 'Fetch' }
r = sess.get(url,auth=(uname,pass),params=params)
token = r.headers
print(r.cookies)
print(token)
print(sess.headers)