ng2-file-upload: "CSRF Failed: CSRF token missing or incorrect" with Django

Hi. I’m using django + django-rest-framework as backend and try to use ng2-file-upload to upload file, but failed with CSRF token missing.

I think I’ve correctly setup XSRFStrategy so other POST/PUT/DELETE requests work, and when uploading in request header there’s csrftoken in the cookie, but seems ng2-file-upload doesn’t work with CSRF token very well.

Here’s request header:

POST /api/upload/ HTTP/1.1
...
...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhMZfMzgtFvJcsxRZ
Accept: */*
Referer: http://foo.bar/uploader/
Cookie: sessionid=SID; csrftoken=CSRFTOKEN

Thank you very much

About this issue

Most upvoted comments

In case you are using the HttpClientXsrfModule to add an XSRF Header, there is a simpler solution to get the XSRF Token.

Simply inject HttpXsrfTokenExtractor from ‘@angular/common/http’. To get the token call const token = this.httpXsrfTokenExtractor.getToken();

The full code could be :

import { FileUploader, FileUploaderOptions } from 'ng2-file-upload/ng2-file-upload';
import { HttpXsrfTokenExtractor } from '@angular/common/http';
...
  constructor(private xsrfService: HttpXsrfTokenExtractor) {
    this.uploader = new FileUploader({ url: url });
    this.uploader.options.headers = [
      { name: 'X-XSRF-TOKEN', value: this.xsrfService.getToken() }
    ];
  }

In case you are using the HttpClientXsrfModule to add an XSRF Header, there is a simpler solution to get the XSRF Token.

Simply inject HttpXsrfTokenExtractor from ‘@angular/common/http’. To get the token call const token = this.httpXsrfTokenExtractor.getToken();