Skip to Content
Technical Articles
Author's profile photo ASUTOSH MAHARANA

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%20Value%20Map%20for%20Backend%20Credential

Key Value Map for Backend Credential

  • Then we will implement below 4 policies in target endpoint.

Policy

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

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>

 

 

Assigned Tags

      24 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo prachetas singh
      prachetas singh

      Great blog Asutosh.

      Author's profile photo Olesya Chekhonina
      Olesya Chekhonina

      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

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      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

      Author's profile photo Olesya Chekhonina
      Olesya Chekhonina

      Asutosh, thank you for your quick answer.

      I added what you wrote, but now have an error:

      "Unresolved variable : request.header.OAuthToken"
      and
      May be something wrong with any other settings?
      Best Regards,
      Olesya
      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      Dear Olesya,

      You have done a little bit wrong. in the amOAuthToken policy you are changing the "response". Kindly put below xml.

      <!-- 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="OAuthToken">{request.header.Authorization}</Header>
          </Headers>
      	</Set>
      	<IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
      	<AssignTo createNew="false" type="request">request</AssignTo>
      </AssignMessage>

      Check the "AssignTo" in the xml.

      BR,

      Asutosh Maharana

      Author's profile photo Olesya Chekhonina
      Olesya Chekhonina

      Asutosh, thank you.

      I changed the xml as you mentioned,

      but now in Postman i am getting:

      {
          "fault": {
              "faultstring": "Execution of ServiceCallout scCSRF failed. Reason: ResponseCode 401 is treated as error",
              "detail": {
                  "errorcode": "steps.servicecallout.ExecutionFailed"
              }
          }
      }
      And in the debug I see the following:
      May by Api base path is wrong
      Regards,
      Olesya
      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      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

      Author's profile photo Olesya Chekhonina
      Olesya Chekhonina

      Asutosh, I have created a new product and assigned my api proxy.

      I am still struggling with the error:

      {
          "fault": {
              "faultstring": "Execution of ServiceCallout scCSRF failed. Reason: ResponseCode 401 is treated as error",
              "detail": {
                  "errorcode": "steps.servicecallout.ExecutionFailed"
              }
          }
      }
      Here is my settings:

      I use in the "Path" field in Policy "Service Callout" the Path from "Overview" tab of my API. Is it right?

       

      Regards,

      Olesya

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      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

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      API Base path with /

      Do not remove / while putting it in Service callout.

      Author's profile photo Olesya Chekhonina
      Olesya Chekhonina

      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

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      Dear Olesya,

      it's working fine for me. Please do the following.

      1. assign your Oauth Generator and oauth verifier api proxy to the same product.
      2. use the csrf token handling policies to oauth verifier flow. with service call out base path as the oauth verifier api proxy. and please assign oauth verifier policy and the assign message policy in the proxy endpoint preflow.
      3. create appication for that product.
      4. use that app keys to generate the oauth token.
      5. then use that token to make call to the oauth verifier api proxy.

      I have done the same and it was working fine.

      if issues kindly connect me over linkedin i may help you.

      BR,

      asutosh maharana

      Author's profile photo Olesya Chekhonina
      Olesya Chekhonina

      Asutosh, thank you very much.

      It really helped.

      The problem was solved by adding the resource in the API base path.

       

      Kind regards,

      Olesya.

      Author's profile photo Chamode-Anjana Hewawasam-Puwakpitiyage
      Chamode-Anjana Hewawasam-Puwakpitiyage

      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:

      error:Execution of ServiceCallout scCSRF failed. Reason: ResponseCode 404 is treated as error
      type:ErrorPoint
      state:TARGET_REQ_FLOW
      error.class:com.apigee.kernel.exceptions.spi.UncheckedException
      error.cause:ResponseCode 404 is treated as 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

      Author's profile photo Keerthana Jayathran
      Keerthana Jayathran

      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

      Author's profile photo Sudhir Yesu
      Sudhir Yesu

      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

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      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

       

      Author's profile photo Sudhir Yesu
      Sudhir Yesu

      Thanks Asutosh. Now, it is working as expected.

      Author's profile photo Joao Tiago Ribeiro
      Joao Tiago Ribeiro

      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

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      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

      Author's profile photo Joao Tiago Ribeiro
      Joao Tiago Ribeiro

      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

      Author's profile photo GowruVamsidhar Reddy
      GowruVamsidhar Reddy

      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

      Author's profile photo ASUTOSH MAHARANA
      ASUTOSH MAHARANA
      Blog Post Author

      Dear,

      Please remove this variable from amCSRF (AssignMessage) policy. Just like Below. May be your Backend is only giving 2 cookies.

       

      <!-- 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</Header>
          </Headers>
      	</Set>
      	<IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
      	<AssignTo createNew="false" type="request">request</AssignTo>
      </AssignMessage>
      Author's profile photo GowruVamsidhar Reddy
      GowruVamsidhar Reddy

      Hello,

      I have changed it and now it's working fine.

       

      Thank you so much!!