How to Handle CSRF Token in SAPUI5
What’s CSRF Token
A string to identify that the request is legit.
Server Side
Changing the Default CSRF Protection Mechanism123
To change the default CSRF protection mechanism, proceed as follows:
-
Go to transaction
SICF
. -
Navigate to the ICF node for your service.
-
Double-click your service node.
-
On Service Data choose GUI Configuration.
Caution: The value of GUI link must remain Not specified.
-
Enter the following values:
-
Parameter Name:
~CHECK_CSRF_TOKEN
-
Parameter Value:
0/1
(disable/enable)-
Compatiblity Mode for SP02 – HTTP Handler in
SICF
(nodesdata
)(Default :
X-Requested-With
, to enable XSRF check use,~CHECK_CSRF_TOKEN=1
)The request handler is
/IWFND/CL_SDATA_ODATA_APP
. -
Standard Mode – HTTP Handler in
SICF
(nodeodata
)(Default:
XSRF check
, to disable and switch toX-Requested-With
, use~CHECK_CSRF_TOKEN=0
)The request handler is
/IWFND/CL_SODATA_HTTP_HANDLER
.
-
-
-
Choose Continue and save your settings.
Client Side2
Get CSRF Token From Server
When you instantiate the OData model, it will get the token if enabled.
// OData model is default to handling the token automatically.
// let oModel = new sap.ui.model.odata.v2.ODataModel('service_url',{tokenHandling: true});
let CSRFToken = oModel.getSecurityToken()
//from view
let CSRFToken = this.getView().getModel().oHeaders[‘x-csrf-token’]
// get a new token
oModel.refreshSecurityToken(succss => {
// success handler, you should be able to get the new token
}, err => {
// error handler
}, false)
Note: the token WON’T be ready at the
onInit
method, you have to wait tillonAfterRendering
Send CSRF Token to Server
Send the token in parameter x-csrf-token
within the request header.
let headerParma = new sap.ui.unified.FileUploaderParameter();
headerParma.setName(‘x-csrf-token’);
headerParma.setValue(CSRFToken);
oUpload.addHeaderParameter(headerParma);
FileUploader
Unfortunately, FileUploader has nothing to do with OData model, so you have to handle it by yourself.
3rd Party Tool
You first need to send the request to get the token by using the request header parameter: *X-CSRF-Token : Fetch*
.
Once you have the token, you can use it as the header parameter while sending your request.
https://help.sap.com/saphelp_gateway20sp12/helpdata/en/e6/cae27d5e8d4996add4067280c8714e/content.htm
https://blogs.sap.com/2014/07/11/issues-with-csrf-token-and-how-to-solve-them/