我需要 jQuery .ajax() 的 CSRF 令牌吗? [英] Do I need a CSRF token for jQuery .ajax()?

查看:24
本文介绍了我需要 jQuery .ajax() 的 CSRF 令牌吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个基本的 .ajax() POST 方法到 PHP 文件.

So I've got a basic .ajax() POST method to a PHP file.

我需要什么安全措施?

周围的一些帖子提到使用您通过 AJAX 发送并在 PHP 文件中验证的隐藏 MD5 输入字段.这是一个足够好的方法吗?

A few posts around were mentioning using a hidden MD5 input field that you send via AJAX and verify in the PHP file. Is this a good enough method?

推荐答案

CSRF 的风险在于外部站点可能会将数据发送到您的站点,而用户浏览器会自动将身份验证 cookie 与它一起发送.

The risk from CSRF is that an external site could send data to yours and the users browser will automatically send the authentication cookie along with it.

您需要的是接收操作(您的 $.ajax() 方法正在向其发送 POST 数据)的某种方式,以便能够检查请求是否来自您的另一个页面网站,而不是外部网站.

What you need is some way for the receiving action (that your $.ajax() method is sending POST data to) to be able to check that the request has come from another page on your site, rather than an external site.

有几种方法可以做到这一点,但推荐的方法是向请求添加一个令牌,您可以检查该令牌而黑客无法访问该令牌.

There are a couple of ways to do this, but the recommended way is to add a token to the request that you can check for and that the hackers can't get to.

最简单的:

  • 登录时创建一个长随机字符串令牌并将其保存给用户.
  • 向包含令牌的 $.ajax() 请求添加一个参数.
  • 根据请求检查令牌是否与您为用户保存的令牌匹配.
  • 如果令牌不匹配,您就有了 CSRF hack.

黑客无法访问您的数据库,也无法实际读取您发送给用户的页面(除非他们受到 XSS 攻击,但这是另一个问题),因此无法欺骗令牌.

The hacker can't get to your DB and can't actually read the page you've sent to the user (unless they get an XSS attack in, but that's another problem) so can't spoof the token.

令牌最重要的是你可以预测(并验证)它而黑客不能.

All that matters with the token is that you can predict (and validate) it and that the hacker can't.

出于这个原因,最容易生成长而随机的内容并将其存储在数据库中,但您可以构建一些加密的内容.不过,我不会只对用户名进行 MD5 - 如果 CSRF 攻击者弄清楚如何生成您的令牌,您就会被黑客入侵.

For this reason it's easiest to generate something long and random and store it in the DB, but you could build up something encrypted instead. I wouldn't just MD5 the username though - if the CSRF attackers figure out how to generate your tokens you'll be hacked.

另一种方法是将令牌存储在 cookie(而不是您的数据库)中,因为攻击者无法读取或更改您的 cookie,只会导致它们被重新发送.那么你就是 HTTP POST 数据中的令牌匹配 cookie 中的令牌.

Another way is to store the token is in a cookie (rather than your database), as the attackers can't read or change your cookies, just cause them to be re-sent. Then you're the token in the HTTP POST data matches token in the cookie.

您可以使这些更加复杂,例如每次成功使用时都会更改的令牌(防止重新提交)或特定于用户和操作的令牌,但这是基本模式.

You can make these a lot more sophisticated, for instance a token that changes every time it's successfully used (preventing resubmission) or a token specific to the user and action, but that's the basic pattern.

这篇关于我需要 jQuery .ajax() 的 CSRF 令牌吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆