Search code examples
javascriptangularheadercsrfcsrf-protection

Can't access property from POST response headers in Angular 4


I'm trying to access CSRF Token received from POST response header, which I need to send back with every further request from my app. I'm was able to drill down the response stream until I could access the [[Entries]] which has the "csrfpreventionsalt" token. It gets displayed in console but when trying to access it shows as undefined.

Tried & Tested: I've tried the "get" method to access the header but it didn't work.

var csrf = res.headers.get('csrfpreventionsalt');

I've seen other questions on SO which say that you can't access the header value but If I can access the header in console then definately I should be able to access the token & assign it to a variable.

Solution to this might help others as well who could face the same situation in their apps. Any help is welcome !!

enter image description here enter image description here


Solution

  • I was calling the get method after calling the json() method, basically I could get the csrf value after accessing it in the raw response object like below:

    private extractLoginData = (res: Response) => {
        this.csrfToken = res.headers.get('csrfPreventionSalt');
        let body = res.json();
        return body;
    }
    

    Also make sure that you have your service has set the header fields as "*" for Access-Control-Allow-Headers & Access-Control-Allow-Origin.

    Also add your "Access-Control-Allow-Credentials: true".