0

I use the standard way of using X-CSRF-TOKEN in Angular 2 like this in my app.module:

provide: XSRFStrategy, useValue: new CookieXSRFStrategy('CSRF-TOKEN', 'X-CSRF-TOKEN')

I am using "primeng" for file-upload. I need to set up the token by my self like this:

private onBeforeSend(event) {
     event.xhr.setRequestHeader("X-CSRF-TOKEN", tokenThatINeed);
}

I need that token that Angular2 has generated for me. I don't know how to access the token.

user2959870
  • 80
  • 6
  • 25

3 Answers3

1

you can get your token with the following code

document.cookie
1

Use the HttpXsrfTokenExtractor like this:

export class MyComponent {

    constructor(csrfTokenExtractor: HttpXsrfTokenExtractor) {
        console.log(csrfTokenExtractor.getToken());
    }
}
yankee
  • 38,872
  • 15
  • 103
  • 162
0

So, I had a similar issue, and used a 3rd party javascript library to solve the problem. There are a few different ones, but I used angular2-cookie. Once you inject the Service into your Component its pretty straight forward. Here's what my code ended up looking like:

import {CookieService} from "angular2-cookie/core";

@Component({
    selector: 'fileUpload',
    templateUrl: 'app/components/files/fileUpload.html',
    providers: [CookieService]

})

export class FileUploadComponent {
    uploadUrl:string;

    constructor(private propertyService:PropertyService,
                private cookieService:CookieService){

        this.uploadUrl = propertyService.getProperties().server_location + "/files/upload"
    }

    onBeforeSend(event:any){
        event.xhr.open("POST", this.uploadUrl, true);
        event.xhr.setRequestHeader("X-XSRF-TOKEN", this.cookieService.get("XSRF-TOKEN"));
    }
}
user2875462
  • 367
  • 3
  • 5