gpt4 book ai didi

javascript - 为什么要将 CSRF token 放入 JWT token 中?

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:26 24 4
gpt4 key购买 nike

我想对 Stormpath post 中的 JWT token 和 CSRF 提出疑问解释了将 JWT 存储在 localStorage 或 cookie 中的优点和缺点。

[...] if you are reading values out of a cookie using JS, that means youcan't set the Httponly flag on the cookie, so now any JS on your sitecan read it, thus making it the exact same security-level as storingsomething in localStorage.

I'm trying to understand why they recommend adding the xsrfToken tothe JWT. Doesn't storing your JWT in the cookie and then extracting itout and placing the JWT in the HTTP header and authenticating therequest based on the HTTP header accomplish the same thing asAngular's X-XSRF-TOKEN? No other domain could make requests on auser's behalf if you authenticate based on the JWT in the header,since other domains cannot extract the JWT from the cookie. I don'tunderstand the purpose of the xsrfToken in the JWT - perhaps its justan additional layer of defense - meaning that attackers would have tohave a compromised script on your site and CSRF a user at the time. Sothey'd have to hit you in both ways to be able to pull of an attack.

帖子链接在this answer哪里说:

The last thing is to ensure that you have CSRF protection on everyHTTP request to ensure that external domains initiating requests toyour site cannot function.

[...] Then, on every request into your server, ensure that your ownJavaScript code reads the cookie value and sets this in a customheader, e.g. X-CSRF-Token and verify that value on every request inthe server. External domain clients cannot set custom headers forrequests to your domain unless the external client gets authorizationvia an HTTP Options request, so any attempt at a CSRF attack (e.g. inan IFrame, whatever) will fail for them.

即使他们可以设置自定义 header ,他们也无法访问存储 JWT token 的 cookie,因为只有在同一域上运行的 JavaScript 才能读取该 cookie。

他们唯一的方法是通过 XSS,但是如果存在 XSS 漏洞,JWT 中的 xsrfToken 也会受到损害,因为在受信任的客户端域中运行的恶意脚本可以访问 cookie 中的 JWT 并在请求中包含 header 使用 xsrfToken。

所以等式应该是:

  • TLS + 存储在安全 cookie 中的 JWT + 请求 header 中的 JWT + 无 XSS 漏洞。

如果客户端和服务器在不同的域中运行,则服务器应发送 JWT,客户端应使用 JWT 创建 cookie。我认为这个等式对于这种情况仍然有效。

更新: MvdD agree with me :

As the browser does not automatically add the header to your request,it is not vulnerable to a CSRF attack

最佳答案

我是 Stormpath 博客文章的作者。在 JWT 中存储 XSRF token 并不是关于它在 JWT 中,而是关于它在 cookie 中。 cookie 应该是 httpOnly,所以你不能从 Javascript 读取它。

现在,我认为引起一点困惑的一点是我谈论 Angular 地方。 Angular 也将它设置为仅 XSRF cookie(不是 httpOnly)以在请求时将其放入 header (这只能由同一域上的 javascript 完成)。这些不是同一个 cookie。

如果您考虑在您的应用程序中实现 XSRF 支持,这已经通过存储服务器端状态和存储 XSRF 的点来完成。将它存储在 httpOnly cookie 中是关于 XSRF 的无状态。在这里,您将验证 JWT 签名,从声明中获取 XSRF,并将其与 header 进行比较。

您的问题的答案是您不需要在服务器上存储状态。

关于javascript - 为什么要将 CSRF token 放入 JWT token 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35013781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com