Introduction
This blog post describes how to call CSRF token internally and post the token in headers using policies in SAP API Management
What is CSRF and what happens if we don’t pass?
CSRF stands for cross site request forgery is a secure token that is used to prevent CSRF attacks. csrf Token is required when ever you are going modify data in backend.
If backend accepts request with out csrf token then there is high chance for the attackers to do calls behalf of user.
you may get error like CSRF validation failed in response when ever you are calling API with methods such as POST ,PATCH ,DELETE. This is because either you are not passing csrf token in headers or passing invalid token
How to Get the token and Pass it to backend?
Generally if we want to get the token we have to pass x-csrf-token and value as fetch in headers for GET API. After successful call we can see CSRF token in response headers. We can copy that token and send it to backend as headers for POST API
Prerequisite
- Subscribe to integration suite and assign all roles to your ID.
- Create API with endpoint as /csrf and also create one more endpoint with any of these methods(POST/PATCH/DELETE)
Note: You can create endpoints by giving paths in swagger
How to Get the token and Pass it to backend using policies in SAP APIM?
- Go to the policies and select any endpoint in left side
- Add Service Callout policy and mention your csrf API path in local target connection tag in the policy
- Add Javascript policy to get the csrf token and cookies from the Service callout response
example code:
var csrf = context.getVariable(“calloutResponse.header.x-csrf-token.values.string”) + “”;
var responsecookies = context.getVariable(“calloutResponse.header.set-cookie.values.string”);
Note: If you get csrf validation failed error even though you are passing valid token then try to pass both csrf token and cookies
- After getting the token and cookies add assign message policy with type as request and add csrf and cookies as request headers
Note: If the endpoint supports both GET and POST calls then you can mention in condition string as verb != GET
Conclusion
This is how we deal csrf token internally by using policies in SAP APIM. So that user no need to call csrf token and post that to backend manually.
Follow my profile to be notified of the next blog post. Please feel free to ask any questions you have in the comments section below.
In the next blog I will explain about how to cache CSRF token using lookup and populate cache policies.
Hope you liked my first blog 🙂