sql - 如何清理 Rails API 参数

标签 sql ruby-on-rails ruby api

我正在制作自己的 API,我想知道:如何保护接收到的参数?

例子:

  • 我有一个具有 brandcolor 属性的汽车模型。

我的端点在有效载荷中接收这些参数。有了这个接收到的有效载荷,我在我的数据库中搜索:

car = Car.where(color: params[:color])
# or
car = Car.find_by(brand: params[:brand])
# or writing
Car.first.update!(brand: params[:brand])

但我很担心如果有人试图利用 SQL 或 XSS 进行攻击怎么办? 你如何使用它?

非常感谢:)

最佳答案

您问题中的示例都自动防止 SQL 注入(inject)。

相关引自官方Rails Guides :

7.2.1 Introduction

SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:

Project.where("name = '#{params[:name]}'")

然后在 same document 中:

7.2.4 Countermeasures

Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character, and line breaks. Using Model.find(id) or Model.find_by_some thing(something) automatically applies this countermeasure. But in SQL fragments, especially in conditions fragments (where("...")), the connection.execute() or Model.find_by_sql() methods, it has to be applied manually.

Instead of passing a string, you can use positional handlers to sanitize tainted strings like this:

Model.where("zip_code = ? AND quantity >= ?", entered_zip_code, entered_quantity).first

The first parameter is a SQL fragment with question marks. The second and third parameter will replace the question marks with the value of the variables.

You can also use named handlers, the values will be taken from the hash used:

values = { zip: entered_zip_code, qty: entered_quantity }
Model.where("zip_code = :zip AND quantity >= :qty", values).first

Additionally, you can split and chain conditionals valid for your use case:

Model.where(zip_code: entered_zip_code).where("quantity >= ?", entered_quantity).first

关于sql - 如何清理 Rails API 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70654292/

相关文章:

ruby-on-rails - 在 rails i18n 语言环境文件中使用 YAML block

mysql - 转置部分 SQL 结果以合并记录

mysql - 将旧数据库 (MYSQL) 导出到具有不同架构的不同数据库 (SQL Server)

SQL 合并行

mysql - 我应该将多个 ID 存储为 varchar 并使用 FIND_IN_SET 吗?

ruby-on-rails - 如何覆盖事件记录对象中的属性分配?

ruby-on-rails - 你如何在 Rails 4 中存储自定义常量?

ruby-on-rails - 为什么这个 gem 没有向 Rails 应用程序添加 rake 任务?

ruby-on-rails - 加载错误 : Could not open library 'lzo2' : lzo2: cannot open shared object file: No such file or directory

ruby-on-rails - 想要在 ruby​​ 中显示文本字段的前 50 或 60 个单词?