Skip to Content
avatar image
Former Member

FileUploader and X-CSRF-Token?

Hi,

I have a SAPUI5 FileUploader that should post the file to a (NetWeaver Gateway) OData service - which requires that the request has an X-CSRF token. How can I make this happen?

Currently, prior to starting the upload I already did a refreshSecurityToken() on the OData model. But the FileUploader does not pick up this value. How can I proceed here?

Thank you for your help!

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

3 Answers

  • Jul 05, 2013 at 01:58 PM

    Hi Daniel

    Further to the suggestion i made in  http://scn.sap.com/thread/3383994 that I didn't think this was possible with the FileUploader control, I found some time today to investigate further.

    I tried to use a proxy to set the http headers like Jibin Joy suggested in http://scn.sap.com/thread/3262540 the issue like he found was that the data that is posted is encoded as multipart/form-data and the Gateway service is expecting a media resource with the correct content type eg image/gif.

    I managed to get the FileLoader control posting successfully to Gateway services by extending the control, replacing the form.submit with an AJAX call.

    sap.ui.commons.FileUploader.extend("ODataFileLoader", {...     upload : function() {...                    var file = jQuery.sap.domById("upload_1-fu").files[0];                    var oRequest = sap.ui.getCore().getModel(this.getModelName())._createRequest();                    var oHeaders = {                              "x-csrf-token": oRequest.headers['x-csrf-token'],                              "slug": this.getSlug(),                    };                     jQuery.ajax({                              type: 'POST',                              url: this.getUploadUrl(),                              headers: oHeaders,                              cache: false,                              contentType: false,                              processData: false,                              data: file,                              success: _handleSuccess,                              error: _handleError                    });

    The code gets the CSRF token from a nominated Model and uses this with a Slug header that can be dynamically set.

    You can find a working example at https://github.com/jasper07/sapui5bin/blob/master/ODataFileUpload.html

    Cheers

    John P

    Add comment
    10|10000 characters needed characters exceeded

    • Hi Prabaharan,

      Here are the code snippets in reference to my original description for the changes needed to be made on the client side based on UI5 version 1.22.4.

      *It's possible that additional changes/updates are required for the code snippets to be compatible/work in newer version of UI5.

      Client side (UI5 ver 1.22.4)

      -----------------

      - In the UI5 client, for IE8 and IE9, add the x-csrf-token and slug (if you need it) value as hidden input value to the upload form.  For newer browser (Chrome, IE10 etc.) , these values are added to the http request header.

           Override the function sap.ui.unified.FileUploader.prototype.upload.  Since we want to keep the existing      implementation for non IE8 and non IE9 browsers,  the changes we add should only apply to IE8 and      IE9.  In this function, there should already be a check for 'window.File'.   We'll add the following code to      set the header parameters as hidden input fields to the form when 'window.File' returns false. 

           if (this.getSendXHR() && window.File) {

               ....

           }

           else {

           if (sap.ui.Device.browser.msie && (sap.ui.Device.browser.version==8           || sap.ui.Device.browser.version==9)) {

                if (this.getHeaderParameters()) {

                  var oHeaderParams = this.getHeaderParameters();

                  for (var i = 0; i < oHeaderParams.length; i++) {

                       var sHeader = oHeaderParams[i].getName();

                       var sValue = oHeaderParams[i].getValue();

                       if(sHeader=='x-csrf-token' || sHeader=='slug'){

                            var el = document.createElement('input');

                            el.type = 'hidden';

                            el.name = sHeader;

                            el.value = sValue;

                            uploadForm.appendChild(el);

                       }

                  }

               }

           }

           uploadForm.submit();

         }

      - You can look up how to retrieve the upload form by looking at the upload method implementation for the FileUploader control in UI5 source code.

           The uploadForm should already be available in the overridden method (see above).

      - For IE8 and IE9, set a different value (external alias defined below) for the uploadurl attribute of the fileuploader control.

           // Call updateSecurityToken() from your model

           var oFileUploader = new sap.ui.unified.FileUploader({

                ...     

              sendXHR: true,

              useMultipart: true,

              headerParameters: [

              new sap.ui.unified.FileUploaderParameter({

                  name: 'x-csrf-token',

                  value: your csrf token value

              }),

              // if you need 'slug'

              new sap.ui.unified.FileUploaderParameter({

                  name: 'slug',

                  value: your slug value

              })

              ]

           })

           oFileUploader.setUploadUrl(url);

           // For IE8 and IE9, the url value would be the external alias of your custom handler

           // For all other browser, it will be your default service url for file upload

      Thanks,

      Andrew

  • Apr 07, 2014 at 08:50 AM

    Hi,

    When I tried with the above example code I am getting  the following error.

    In console I am getting undefined i.e console.log(oRequest.headers['x-csrf-token']);

    and in network tab I am getting CSRF token validation failed error.

    I don't know where I have done mistake.

    Help me to solve this issue.

    Thanks&Regards

    Sridevi


    upload.jpg (46.2 kB)
    Add comment
    10|10000 characters needed characters exceeded

    • Former Member

      Hello,

      I am using this sap.ca.ui.unified fileuploader control to upload only xml type files.

      After uploading first time, if I try to upload in the same session again. I got error: CSRF token validation failed because for every POST request CSRF token should be changed.

      I have used oModel.updateSecuritytoken() and refreshSecurityToken are giving the same XCRF token in the method: handlValueChange() on new file upload.

      How to get new CSRF token in the same session without service request?

      I am facing this issue from long time. please help me.

  • avatar image
    Former Member
    Apr 16, 2015 at 09:27 AM

    Just figure out the solution, UI5 FileUploader have method to add HTTP header, following code works for me:

    fileUpLoader.setSendXHR(true); //Must set to true, otherwise HTTP headers not be added

    var csrfToken = //get you CSRF token

    fileUpLoader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({

         name: "X-CSRF-Token", value: csrfToken

    }));

    See UI5 API doc for more details.

    Add comment
    10|10000 characters needed characters exceeded