Angular sets the X-XSRF-TOKEN
header to the value of the XSRF-TOKEN
cookie:
var xsrfValue = isSameDomain(config.url, $browser.url())
? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
But, if one sets the XSRF-TOKEN
cookie using $cookieStore
(for Rails integration, for example):
$cookieStore.put("XSRF-TOKEN", "my_token");
the cookie is stored as JSON string:
put: function(key, value) {
$cookies[key] = angular.toJson(value);
}
This means that the header will have the extra double quotes:
X-XSRF-TOKEN "my_token"
Why Angular doesn't call fromJson()
when it sets the value of the header so that the header will look like this:
X-XSRF-TOKEN my_token
?
That would save us from removing the extra double quotes on the server side.
Am I missing something obvious here?
Note: I'm not looking for workarounds. I'm trying to understand whether this behavior is the intended behavior, and if yes, what is the rationale?
The CSRF token value is obtained from the csurf middleware via the req. csrfToken() function. By default, AngularJS will look for this cookie named XSRF-TOKEN and put its value into the X-XSRF-TOKEN header on subsequent requests.
Here is the official answer I got:
The real problem here is that you are trying to use the $cookieStore for the wrong purpose. The $cookieStore is an abstraction on top of $cookie, which works with objects and serializes them to JSON. If you want to assign the XSRF token then just use $cookie to write it, which works directly with strings.
In other words, one should do:
$cookies["XSRF-TOKEN"] = "my_token"; // Stored as: my_token
rather than:
$cookieStore.put("XSRF-TOKEN", "my_token"); // Stored as: "my_token"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With