JWT 和 CSRF 令牌工作流程

JWT and CSRF Token Workflows

我有一个涉及两个微服务的架构。工作流程如下:

现在,鉴于我对 CSRF 和 JWT 令牌的了解有限,我目前使用以下代码进行重定向

res.setCookie('jwt_signed', token, ...);
res.redirect('localhost:3000');

然后在服务 2 中,我解码并验证签名令牌以检查传递的数据的完整性。此外,我还看到在 cookie 中传递的 CSRF 令牌。

现在,我感到困惑的是,由于我正在重定向到服务 2 以进行任何进一步的操作,CSRF 令牌如何从安全 POV 中发挥作用?在 cookie 中发送 JWT 签名令牌是否是安全的良好做法?

此外,将 CSRF 令牌添加到 JWT 签名令牌是否是个好主意?

初始问题

让我一一回答你的问题。

CSRF(跨站点请求伪造)令牌很有用,因为它意味着没有人可以劫持您的 session 并从另一个选项卡(使用您的 session).它的工作原理是在每次加载表单时生成一个令牌,然后在提交此表单时令牌需要匹配。

参见:https://portswigger.net/web-security/csrf AND https://owasp.org/www-community/attacks/csrf

  1. 我不认为在 cookie 中发送任何重要内容是好的做法。您应该改为将其设置为请求 header。 Cookie 很容易被窃取和复制。如果有人复制了 cookie,他们就可以进行身份​​验证。此外,JWT header 与 https 结合使用时将是安全的,因此您也可以进行加密。

例如req.session.myToken = jwt.sign(insideToken, "password");

  1. 您可以将 CSRF 令牌放入 JWT 令牌中。它不一定会造成伤害,它会让你的 JWT header 对于每个请求都更加随机。

除了JWT inside requestheader,强烈推荐HTTPS。否则使用嗅探器的中间人攻击很容易破坏您的安全。

更新

解释 CSRF 的精彩文章如下:https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

您可以生成令牌 server-side 并且您不一定要有表格。您可以将它们放在 session 上。请注意:

Per-request tokens are more secure than per-session tokens as the time range for an attacker to exploit the stolen tokens is minimal. ... When a request is issued by the client, the server-side component must verify the existence and validity of the token in the request compared to the token found in the user session. If the token was not found within the request, or the value provided does not match the value within the user session, then the request should be aborted, session of the user terminated and the event logged as a potential CSRF attack in progress.

CSRF tokens should be:

Unique per user session. Secret Unpredictable (large random value generated by a secure method). CSRF tokens prevent CSRF because without token, attacker cannot create a valid requests to the backend server.

CSRF tokens should not be transmitted using cookies.

The CSRF token can be added through hidden fields, headers, and can be used with forms, and AJAX calls. Make sure that the token is not leaked in the server logs, or in the URL. CSRF tokens in GET requests are potentially leaked at several locations, such as the browser history, log files, network appliances that log the first line of an HTTP request, and Referer headers if the protected site links to an external site.

来源:https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

那篇文章中有很多有用的有趣信息