【问题标题】:Unable to validate Antiforgery token when cookie is set to httponlycookie 设置为 httponly 时无法验证防伪令牌
【发布时间】:2020-04-27 01:34:47
【问题描述】:

当我设置 httponly=true 的值时。 AutoValidateAntiforgeryTokenAttribute 不验证请求并返回 400 bad request

AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(context);
   context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
    new CookieOptions() { HttpOnly = true});

做完这个cookie后就变安全了,如下图所示

set-cookie: XSRF-TOKEN={{Cookie Value}}; path=/; samesite=lax; httponly

但 AutoValidateAntiforgeryTokenAttribute 返回 400 错误请求

when changed the Value HttpOnly = true to HttpOnly = false

它工作得很好。有没有办法在 asp core 和 angular 7 中将 antiforgerytoken cookie 设置为 httponly。如果它不起作用,请一些机构指导我了解其背后的原因。

【问题讨论】:

    标签: c# angular asp.net-core antiforgerytoken cookie-httponly


    【解决方案1】:

    不,不能将此特定 cookie 设置为仅限 http。要了解为什么,请查看 ASP.NET Core docs 的以下部分:

    AngularJS 使用约定来处理 CSRF。如果服务器发送一个名为 XSRF-TOKEN 的 cookie,AngularJS 的 $http 服务会在向服务器发送请求时将 cookie 值添加到标头中。

    这里谈到了 AngularJS 和 $http,但同样的机制也用于 Angular 及其 HttpClient 服务(参见 Angular docs)。

    为了能够将 cookie 值添加到标头,Angular 必须能够读取 cookie 中的值。当您将 cookie 设置为 HttpOnly 时,Angular 无法从 cookie 中读取值(就好像它甚至不存在一样)。因此该值未发送,服务器拒绝请求。

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 2018-06-19
      • 2018-02-04
      • 2014-01-23
      • 1970-01-01
      • 2018-04-13
      • 2019-05-13
      • 1970-01-01
      相关资源
      最近更新 更多