javascript - Ruby on Rails : Difference of Authenticity Token being in Header or POST

标签 javascript ruby-on-rails ruby authenticity-token

我刚刚注意到,通过 AJAX 提交请求时,将我的 Authenticity Token 放在哪里并不重要。我可以将其作为 POST 数据 附加到表单中,或者将其放入 Header 中。

有什么区别吗?特别是在安全方面?

另外:

我没有在 Javascript 中对 token 进行编码。我现在接触过什么东西吗?

提前致谢。

编辑:

form.on("sending", function(file, xhr, formData) {
   xhr.setRequestHeader('X-CSRF-Token', AUTH_TOKEN);
   // formData.append('authenticity_token', AUTH_TOKEN);
});

这是我的 Javascript 将 token 添加到 Header 或(注释掉)到 POST 数据AUTH_TOKEN 是原始 key 。我没有以任何方式对其进行编码。

最佳答案

第一部分

如果您通过 GET 参数、POST 数据或请求 header 传递真实性 token ,则完全没有区别(POST/GET 参数在 Rails 中实际上是相同的)。

让我们看一下代码(不是我见过的最好的代码,但是......)

def verified_request?
  !protect_against_forgery? || request.get? || request.head? ||
    form_authenticity_token == params[request_forgery_protection_token] ||
    form_authenticity_token == request.headers['X-CSRF-Token']
end

请求是否有效(以下任一条件)

  1. protect_against_forgery? 为 false
  2. 请求是 GET
  3. 请求是 HEAD
  4. 参数中的 token 等于 session 中存储的 token
  5. header 中的 token 等于 session 中存储的 token

我应该补充一点, token 是为每个请求生成的,并存储在 session 中以供以后检查(如果后续请求是 POST/PUT/PATCH/DELETE)

正如您所见,传递真实性 token 的两种方法都是有效的。

第二部分

在 AJAX 中传递原始身份验证 token 是否危险?不,只要以某种形式传递它就完全没有危险。为了进一步解释,我将在另一个SO问题中引用一个很好的答案

Why this happens: Since the authenticity token is stored in the session, the client can not know its value. This prevents people from submitting forms to a rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is ok. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to http://serviceA.com/close_account. This is what is known as CSRF (Cross Site Request Forgery).

原答案:https://stackoverflow.com/a/1571900/2422778

我仍然认为这个问题是你的懒惰/缺乏耐心,因为我写的所有内容在 Rails Guides 和 Stack Overflow 上都得到了很好的解释。希望下次您在发帖之前能更加坚持寻找答案。
不管怎样,我很高兴能提供帮助。

关于javascript - Ruby on Rails : Difference of Authenticity Token being in Header or POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20905246/

相关文章:

javascript - 使用 Twilio IP Messaging 进行私有(private)消息传送

ruby-on-rails - 当我们在 View 中访问未定义的实例变量时,为什么 Rails 不抛出异常?

ruby - 无法使用 RVM 在 Lion 下安装 Ruby – GCC 问题

ruby - 使用 AWS ruby​​ sdk 时出现错误 "The security token included in the request is invalid"

javascript - 在 SpannableString 上设置拖动监听器

Javascript 如果为空则不起作用?

javascript - 三星数字健康 Android SDK + Tizen Web 开发

ruby-on-rails - 在方法之间传递数据时的正确技术

ruby-on-rails - 在 rails 和 postgresql 中使用键值进行不区分大小写的搜索

jquery - 数据库值不会反射(reflect)到 jQuery UI slider