Technical Articles
CSRF Token handling in SAP API Management
Introduction
While exposing SAP GW OData services via SAP APIM (API management), we have encountered one simple requirement to enable server to server authentication between S/4 Hana and SAP APIM system. So that the API consumers will not have to know backend system credentials and they can use policy based APIKey or OAuth 2.0 kind of authentication from Developer portal. Whenever we will make POST, PUT and DELETE HTTP verb, it will require CSRF token validation from backend, so we will try to automate that as well from API management layer.
Main
I will not explain how to expose OData service using SAP APIM in this blog. Those are well documented in other blog by Benno Grimm. There are many other blogs as well you can refer.
So, let’s see the policies required to enable backend authentication from APIM.
- Key value map:
We have created a Key value map for storing credential of backend system.
Key Value Map for Backend Credential
- Then we will implement below 4 policies in target endpoint.
Policy
- kvmFetch (KeyValueMapOperations):
This policy will help to retrieve username and password from key value map and assign them to private variables. No condition string required for this policy.
<KeyValueMapOperations mapIdentifier="ES5Credential" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">
<Get assignTo="private.BasicAuthUsername" index='1'>
<Key><Parameter>Username</Parameter></Key>
</Get>
<Get assignTo="private.BasicAuthPassword" index='1'>
<Key><Parameter>Password</Parameter></Key>
</Get>
<Scope>environment</Scope>
</KeyValueMapOperations>
- baAuth (BasicAuthentication):
This policy will help to encode the username and password in Base64 and assign that to Authorization header. No condition string required for this policy.
<BasicAuthentication continueOnError='false' enabled='true' xmlns='http://www.sap.com/apimgmt'>
<Operation>Encode</Operation>
<IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
<User ref='private.BasicAuthUsername'></User>
<Password ref='private.BasicAuthPassword'></Password>
<AssignTo createNew="true">request.header.Authorization</AssignTo>
</BasicAuthentication>
- scCSRF (ServiceCallout):
This policy will help to fetch CSRF token from backend call. Please put below as Condition string. I have used an API provider named ES5 for backend connection in APIM.
(request.verb = "POST" OR request.verb = "PUT" OR request.verb = "DELETE")
<?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>ES5</APIProvider>
<Path>sap/opu/odata/IWFND/CATALOGSERVICE/ServiceCollection</Path>
</HTTPTargetConnection>
</ServiceCallout>
- amCSRF (AssignMessage):
This policy will help to assign CSRF token and cookies to the request message. Please put below as Condition string.
(request.verb = "POST" OR request.verb = "PUT" OR request.verb = "DELETE")
<!-- 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>
- Test
We can call from postman.
Testing
Conclusion
I have tried to replicate the same for On-Premises API provided but the service callout policy was failing, but I have used local proxy call in service callout policy and it started working.
<?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>
<LocalTargetConnection>
<Path><API Base Path></Path>
</LocalTargetConnection>
</ServiceCallout>
Great blog Asutosh.
Asutosh,
thank you for your post - it really helps, but I'm facing the issue when trying to send POST request to SAP on-premise system:
{"fault":{"faultstring":"Invalid access token","detail":{"errorcode":"oauth.v2.InvalidAccessToken"}}}
I set Path in the ServiceCallout Policy, but still have a problem. Do you have any ideas how this can be solved?
Regards,
Olesya
Dear Olesya,
I think whatever base path you have mentioned in the service callout policy that might contain a "VerifyAccessToken" OAuth2.0 policy in pre-flow. So you are getting the invalid access token error. you can try assiging the OAuth token first in a variable like below screenshot.
Then you can just basically set up that variable as header in service callout policy.
Please let me know if this solution helps.
BR,
Asutosh Maharana
Asutosh, thank you for your quick answer.
I added what you wrote, but now have an error:
Dear Olesya,
You have done a little bit wrong. in the amOAuthToken policy you are changing the "response". Kindly put below xml.
Check the "AssignTo" in the xml.
BR,
Asutosh Maharana
Asutosh, thank you.
I changed the xml as you mentioned,
but now in Postman i am getting:
Dear Olesya,
Can you use the same base path of your API proxy in the service callout (if you are putting service callout in API Proxy "A" then put the base path of API proxy "A" in the service call out policy ...Kind of a loopback). Please do not use any other API Proxy. and the error you are getting is due to the api proxy base path you are using is not part of any product.
BR,
Asutosh Mahrana
Asutosh, I have created a new product and assigned my api proxy.
I am still struggling with the error:
I use in the "Path" field in Policy "Service Callout" the Path from "Overview" tab of my API. Is it right?
Regards,
Olesya
Dear Olesya,
Add the "OAuth Token Generator" API Proxy as well in that new product and use the application (clientid and client secret) which ever you have subcribed to that new product in dev portal.
BR,
Asutosh Maharana
API Base path with /
Do not remove / while putting it in Service callout.
Asutosh, thank you!
I use exactly like in overview tab - with /
I have product with "OAuth Token generator" and I used it when i didn't add policies about x-csrf-token and it worked fine. But now still have 401
Regards,
Olesya
Dear Olesya,
it's working fine for me. Please do the following.
I have done the same and it was working fine.
if issues kindly connect me over linkedin i may help you.
BR,
asutosh maharana
Asutosh, thank you very much.
It really helped.
The problem was solved by adding the resource in the API base path.
Kind regards,
Olesya.
Hi Asutosh,
Thank you very much for the detailed guide. I am facing some difficulty with a POST call.
I am encountering the following error:
Using the debugger I found the following error:
Would you be able to help here? The error is not encountered for GET calls and only POST calls (as expected)
Best regards,
Chamode
Hi Chamode-Anjana Hewawasam-Puwakpitiyage ,
Did you solve this? I am also facing the same issue.If you resolved it,could you please guide me.
Thanks & Regards,
Keerthana
Hi ASUTOSH MAHARANA,
Thanks for the post. After deploying with the policies, API can be accessed without any credentials (bypassing the credentials in the request). Could you please provide a solution to validate the credentials in the request.
Thanks,
Sudhir Yesu
Dear Sudhir,
You can try removing below 2 policies, then you have to send the credentials from Client side.
kvmFetch and baAuth
Let me know if you have any issues.
Thanks,
Asutosh
Thanks Asutosh. Now, it is working as expected.
Hello dear Asutosh, thank you for the blog.
It's interesting and solves the problem to use APIs to POST actions.
However, what should be used in case we deploy a standard API from a public S/4HANA Cloud instance? I haven't used an API Provider for such.
What should we define in the Policy for the CSRF bypass?
Thank you
Tiago Ribeiro
Dear Tiago,
you can use the service callout policy with "HTTPTargetConnection/URL" element instead of using "HTTPTargetConnection/APIProvider" element. Please go through the below SAP Documentation. Check example 2.
Service callout policy
Thanks,
Asutosh
Thank once again Asutosh. I've checked the help document but was not sure which URL to use.
The API Proxy endpoint or the real api service endpoint?
Another question is if all the 4 policies will be incoming request or outgoing-incoming-outgoing-incoming.
Will try with the element you mentioned.
Thank you
Tiago Ribeiro
Hello ASUTOSH MAHARANA,
thanks for the great blog. I'm facing an issue while connecting with sap cpi using CSRF. In service callout, I'm getting an error. Thanks in advance
Dear,
Please remove this variable from amCSRF (AssignMessage) policy. Just like Below. May be your Backend is only giving 2 cookies.
Hello,
I have changed it and now it's working fine.
Thank you so much!!