user2959870
user2959870

Reputation: 78

Get X-CSRF-TOKEN in Angular 2

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.

Upvotes: 0

Views: 3822

Answers (3)

yankee
yankee

Reputation: 40800

Use the HttpXsrfTokenExtractor like this:

export class MyComponent {

    constructor(csrfTokenExtractor: HttpXsrfTokenExtractor) {
        console.log(csrfTokenExtractor.getToken());
    }
}

Upvotes: 1

user2875462
user2875462

Reputation: 397

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"));
    }
}

Upvotes: 0

user2843943
user2843943

Reputation:

you can get your token with the following code

document.cookie

Upvotes: 1

Related Questions