在REST API端验证CSRF令牌

编程入门 行业动态 更新时间:2024-10-26 02:24:45
本文介绍了在REST API端验证CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在PHP上编写了REST API,并使用基于JWT的身份验证。工作流程很简单:用户发送用户名和密码并获取JWT令牌,并在所有REST请求中对其进行身份验证。一切都是相当逻辑和酷,但现在我有一个存储令牌客户端的问题,经过一些谷歌搜索我发现只有HTTP Only,安全cookie对此有好处,但他们容易受到CSRF攻击,所以我打算用户CSRF令牌解决了这个问题。这里有一个问题,REST如何验证CSRF令牌,如果客户端发出令牌? REST后端如何理解这个随机字符串对此请求有效,而另一个随机字符串不是? REST是无状态的,他不知道什么样的令牌客户端发布,因为REST和客户端在单独的后端,甚至在不同的服务器上。 什么我试过了: REST是无状态的,他不知道什么样的令牌客户端已发布,因为REST和客户端在单独的后端,甚至在单独的服务器上。

解决方案

客户端不发出CSRF令牌。这不安全,也不会提供任何保护。 OWASP为CSRF保护提供了一些建议: Cross-Site Request Forgery(CSRF)预防备忘单 - OWASP [ ^ ] 自定义请求标题 [ ^ ]选项可能是最简单的,但是注意关于使用Flash绕过这个的评论。 哟你可能还想看看你是否可以在你的身份验证cookie中添加SameSite属性: 使用相同站点的cookie属性防止CSRF [ ^ ] Cross-Site Request Forgery已经死了! [ ^ ] Chrome,Opera和Android目前支持; Firefox将在v60中添加支持: 我可以使用......'SameSite' Cookie属性 [ ^ ]

I have REST API written on PHP with authentication based on JWT. Workflow is simple: user sends username and password and gets JWT token back, with what they will be authenticated on all REST requests. Everything is pretty logic and cool, but now I have a problem with storing token client side, after some googling I found what only HTTP Only, Secure cookies are good for this, but they are vulnerable for CSRF attacks, so I am planning to user CSRF token to solve this problem. And here comes the question, how REST can validate CSRF token, if token issued by client? How REST backend understand what this random string is valid for this request and another random string is not? REST is stateless, he doesn't know what kind of token client have issued because REST and client are on separate backend, even on separate servers. What I have tried: REST is stateless, he doesn't know what kind of token client have issued because REST and client are on separate backend, even on separate servers.

解决方案

The client does not issue the CSRF token. That would not be secure, and would not provide any protection. OWASP provides several suggestions for CSRF protection: Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet - OWASP[^] The custom request headers[^] option would probably be the simplest, but pay attention to the comment about using Flash to bypass this. You'll probably also want to see if you can add the "SameSite" attribute to your authentication cookie: Preventing CSRF with the same-site cookie attribute[^] Cross-Site Request Forgery is dead![^] Currently supported in Chrome, Opera and Android; and Firefox will add support in v60: Can I use... 'SameSite' cookie attribute[^]

更多推荐

在REST API端验证CSRF令牌

本文发布于:2023-10-29 09:41:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539364.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   REST   API   CSRF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!