Handle CSRF Tokens in API Management
Enable server-to-server authentication between SAP API Management and the backend system, so API consumers don’t need direct backend credentials.
POST
, PUT
, and DELETE
requests, configure a ServiceCallout scCSRF
policy to automatically
fetch and pass the required X-CSRF token from the backend.To handle CSRF token in API management:
- Select API proxy and click Policies.
- Click Edit.
- Select ProxyEndpoint.
- Select PreFlow.
- Under Extension Policies, choose Service Callout.
- Click on the + button to add the policy.
- Enter the Policy Name, set the Stream as Incoming Request and click Add.
-
Replace the existing default content in the Body section with the following
policy XML and click Update.
Condition String:
(request.verb = "POST" OR request.verb = "PUT" OR request.verb = "DELETE")
Policy Message:<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ServiceCallout async="true" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt"> <Request> <Set> <Headers> <Header name="x-csrf-token">fetch</Header> <Header name="Authorization">{request.header.Authorization}</Header> </Headers> <Verb>GET</Verb> </Set> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> </Request> <Response>callOutResponse</Response> <Timeout>30000</Timeout> <HTTPTargetConnection> <APIProvider>EW8API</APIProvider> <Path>/sap/opu/odata/invicl/ICWP_INTEGRATION_SUITE_SRV</Path> </HTTPTargetConnection> </ServiceCallout>
Note:Make sure to change the API Provider name in the policy, for example:<HTTPTargetConnection> <APIProvider>[Provide API Provider Name here ]</APIProvider> <Path>/sap/opu/odata/invicl/ICWP_INTEGRATION_SUITE_SRV</Path> </HTTPTargetConnection>
- Click Save.
- Enter the Policy Name, set the Stream as Incoming Request, and click Add.
-
Replace the existing default content in the Body section with the following
policy XML, and click Update.
Condition String:
(request.verb = "POST" OR request.verb = "PUT" OR request.verb = "DELETE")
Policy Message:<!-- This policy can be used to create or modify the standard HTTP request and response messages --> <AssignMessage async="false" continueOnError="false" enabled="true" xmlns='http://www.sap.com/apimgmt'> <!-- Sets a new value to the existing parameter --> <Set> <Headers> <Header name="x-csrf-token">{callOutResponse.header.x-csrf-token}</Header> <Header name="Cookie">{callOutResponse.header.Set-Cookie.1};{callOutResponse.header.Set-Cookie.2};{callOutResponse.header.Set-Cookie.3}</Header> </Headers> </Set> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <AssignTo createNew="false" type="request">request</AssignTo> </AssignMessage>
Note:Some customers may receive only two cookies instead of three. In such cases, update the policy accordingly. - Click Save.