我刚刚注意到,通过 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
请求是否有效(以下任一条件)
protect_against_forgery?
为 false- 请求是 GET
- 请求是 HEAD
- 参数中的 token 等于 session 中存储的 token
- 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/