0

ng2-file-upload doesn't send CSRF access tokens alongside the upload request, so i get 403 access forbidden and my upload request is just rejected at once.

2 Answers2

2

in jhipster angular 4, every normal http request has a X-XSRF-TOKEN in the header, but the third party library ng2-file-upload doesn't use http service internally i think. so when you're creating a FileUploader object in your components' constructor you should instantiate it like this:

this.uploader = new FileUploader({url: URL, headers: [{name: 'X-XSRF-TOKEN', value: csrfService.getCSRF()}]});

in which the csrfService is an instance of SCSRFService which is located in your projects SharedServices , and can be injected into your Component.

1

If you token gets changed more frequently, you can also set it per request. In the below example the CSRF token is taken from a cookie. This can be done in your component constructor.

this.uploader = new FileUploader({ url: URL });
this.uploader.onBeforeUploadItem = (fileItem) => {
    fileItem.headers.push({name: 'X-XSRF-TOKEN', value: cookieService.getCookie('XSRF-TOKEN')});
    return fileItem;
};
Tarmo
  • 1,136
  • 13
  • 28