【问题标题】:Why AngularJS sends X-XSRF-TOKEN header as JSON string?为什么 AngularJS 将 X-XSRF-TOKEN 标头作为 JSON 字符串发送?
【发布时间】:2013-05-20 19:04:27
【问题描述】:

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

但是,如果使用 $cookieStore 设置 XSRF-TOKEN cookie(例如,用于 Rails 集成):

$cookieStore.put("XSRF-TOKEN", "my_token"); 

the cookie is stored as JSON string:

put: function(key, value) {
  $cookies[key] = angular.toJson(value);
}

这意味着标题将有额外的双引号:

X-XSRF-TOKEN    "my_token"

为什么 Angular 在设置标头的值时不调用 fromJson() 以使标头看起来像这样:

X-XSRF-TOKEN    my_token

这样我们就不用在服务器端删除多余的双引号了。

我在这里遗漏了什么明显的东西吗?

注意:我不是在寻找解决方法。我试图了解这种行为是否是预期行为,如果是,原因是什么?

【问题讨论】:

  • 我不知道这是否是预期的行为,但它可能具有非常理想的副作用,即阻止 XSRF 令牌在作为 cookie 接收时被识别。毕竟,CSRF 之所以起作用,是因为浏览器会随所有请求发送其 cookie,因此无法正确读取的 cookie 中放错的令牌将有助于防止意外破坏保护。

标签: angularjs angular-http angular-cookies


【解决方案1】:

Here is the official answer I got:

这里真正的问题是您正在尝试使用 $cookieStore 出于错误的目的。 $cookieStore 是在 $cookie,它处理对象并将它们序列化为 JSON。如果你 想要分配 XSRF 令牌然后只需使用 $cookie 来编写它,这 直接使用字符串。

换句话说,应该这样做:

$cookies["XSRF-TOKEN"] = "my_token"; // Stored as: my_token

而不是:

$cookieStore.put("XSRF-TOKEN", "my_token"); // Stored as: "my_token"

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2020-03-30
    • 2018-10-23
    • 2015-09-13
    • 2018-09-06
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多