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

      13 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.