Recently I meet with this cookie issue so I document it as a blog in case any other guys might meet with the same problem.
I am trying to create some Opportunity transaction data by consuming OData service via CL_HTTP_CLIENT. Since this is a update operation which needs to be finished by HTTP POST, so a CSRF token is needed in this HTTP post. Let’s first have a look what is a typical scenario running in Chrome extension postman:
(1) Perform a HTTP get operation with header field x-csrf-token = fetch to get a valid CSRF token from http response header field.
(2) launch a HTTP post request using the CSRF token got from previous step,
And a new opportunity could successfully be created in postman:
However, when I implement the above mentioned scenario in ABAP, I meet with trouble. Instead of the expected successful creation message, I always get the error message “CSRF token validation failed”.
Issue trouble shooting
Let’s go back to postman scenario. Although it seems only the header field x-csrf-token is specified in http request, however there is another field cookie which is added to http request under the hood.
We could get this cookie field from previous HTTP get request which is responsible for CSRF token retrieve:
It means in ABAP implementation, we need to first retrieve BOTH CSRF token and cookie field from the first HTTP GET request, and then added these two fields to the request of second HTTP POST request which actually performs the opportunity creation.
This solution is also explained in this thread usage of CSRF token in ABAP report for POST request.
I just added the complete source code of my implementation here and feel free to reuse it. The ABAP report to create Opportunity by consuming OData service:
zcl_odata_tool
Source code for ZCL_ODATA_TOOL:
CLASS
Further reading
You can find a list of all other blogs related to OData written by Jerry.
- Consume standard C4C OData service via ABAP code
- Leverage C4C Odata notification to monitor C4C Opportunity change in CRM system
- OData Service backend implementation in C4C, CRM and S4 HANA
- JMeter beginner – how to use JMeter to measure performance of OData service accessed parallelly
- Regarding cookie manipulation in CL_HTTP_CLIENT to avoid CSRF token validation failure issue
要获取更多Jerry的原创文章,请关注公众号"汪子熙":