Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why AngularJS sends X-XSRF-TOKEN header as JSON string?

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?

like image 280
Misha Moroshko Avatar asked May 17 '13 13:05

Misha Moroshko


People also ask

How to set CSRF token in AngularJS?

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.


1 Answers

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"

like image 88
Misha Moroshko Avatar answered Oct 02 '22 23:10

Misha Moroshko