简体   繁体   English

使用ajax保护表单提交:有或没有csrf令牌

[英]Protecting form submit with ajax: with or without csrf token

I have a form which is protected with CSRF token. 我有一个受CSRF令牌保护的表单。 I don't know all the details of CSRF tokens but I hear they're good to have for form security. 我不知道CSRF令牌的所有详细信息,但听说它们对于表单安全性很好。 When the form is submitted too late, the form gives an error so the CSRF token appears to be working as intended. 如果表单提交时间太晚,则表单会出现错误,因此CSRF令牌似乎可以正常工作。

On the other hand, when I submit the form with ajax, how can I validate the form the same way I validate a normal form? 另一方面,当我使用ajax提交表单时,如何以与验证普通表单相同的方式来验证表单? I don't think I will have a form object to validate against. 我认为我没有要验证的表单对象。

  • Is there a risk with using ajax? 使用ajax有风险吗?
  • When I accept an ajax call, how can I validate it the same way I validate a normal form? 当我接受ajax调用时,如何像验证普通表单一样验证它?
  • I thought to pass a key with the request (like an API key) to prove that the call is being made from my application, but how can I keep this key from the naked eyes? 我以为可以在请求中传递一个密钥(例如API密钥),以证明该调用是从我的应用程序发出的,但是我怎么能不露面呢?

Is there a risk with using ajax? 使用ajax有风险吗?

Not really any more risk than any other request to your server. 与向您的服务器发出的任何其他请求相比,没有其他风险。

When I accept an ajax call, how can I validate it the same way I validate a normal form? 当我接受ajax调用时,如何像验证普通表单一样验证它?

I don't know, how do you validate the form now? 我不知道,您现在如何验证表格? :) :)

You will probably want to share this code on the server side. 您可能希望在服务器端共享此代码。 Create a common method/function/whatever that processes the form, given key/value pairs. 给定键/值对,创建一个通用的方法/函数/处理表单的所有内容。 The only thing different with AJAX is how the key/value pairs are sent to the server and what the formatted response is. 与AJAX唯一不同的是键/值对如何发送到服务器以及格式化后的响应是什么。 Isolate the validation code from these details and you can just call it from both places. 将验证代码与这些细节隔离开来,您就可以在两个地方都调用它。

Obviously, the AJAX code should send the CSRF token too. 显然,AJAX代码也应该发送CSRF令牌。

I thought to pass a key with the request (like an API key) to prove that the call is being made from my application, but how can I keep this key from the naked eyes? 我以为可以在请求中传递一个密钥(例如API密钥),以证明该调用是从我的应用程序发出的,但是我怎么能不露面呢?

This would be pointless. 这将毫无意义。 JavaScript is sent as plain text, so anyone who knows anything about JavaScript will be able to extract the key. JavaScript以纯文本形式发送,因此任何对JavaScript有任何了解的人都可以提取密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM