如何在 Vapor 4 (Fluent 4) 中使用用户搜索词防止 SQL 注入 [英] How to prevent SQL Injections with User-Search-Terms in Vapor 4 (Fluent 4)

查看:22
本文介绍了如何在 Vapor 4 (Fluent 4) 中使用用户搜索词防止 SQL 注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在实施一个 Vapor 4 应用程序,它将用于管理机器.用户应该能够搜索机器名称,这是我通过

I am currently implementing a Vapor 4 application, which will be used to manage machines. The user should be able to search for a machine name, which I accomplished by

.filter(Machine.path(for: \Machine.$name), .contains(inverse: false, .anywhere), term)

其中 term 是用户提供的任意 String.代码本身按预期工作,但我想知道是否存在 SQL 注入漏洞(或其他攻击).

where term is an arbitrary String provided by the user. The code itself works as intended, but I was wondering if there is the possibility of a SQL Injection vulnerability (or other attacks).

我的问题:
SQL 注入(或其他攻击)是否可能发生,如果可能,我该如何预防(请提供代码示例)?

推荐答案

由于您使用 Fluent,SQL 注入被自动阻止,您很高兴!

Since you are using Fluent, SQL injection is prevented automatically and you are good to go!

而不是简单地构建这样的查询:

Instead of simply constructing a query like this:

SELECT * FROM machines WHERE name = '\(user_provided_name)'

Fluent 使用值绑定,这是数据库提供的一项功能,用于将值传递到查询中,以便在字符串包含 SQL 代码时对值进行转义并且不会被执行.它看起来像这样:

Fluent uses value binding, which is a feature provided by databases to pass values into the query so that the value is escaped and won't be executed if the string contains SQL code. It looks something like this:

SELECT * FROM machines WHERE name = ?

然后这些值通过查询传递到数据库服务器(在本例中为 MySQL),在那里它会自动用提供的值替换占位符 (?).

And then the values are passed to the database server (MySQL in this case) with the query, where it automatically replaces the placeholders (?) with the values provided.

对您的查询进行快速评论,如果需要,您可以导入 FluentSQL 模块,然后像这样编写您的查询:

A quick comment on your query, if you want, you can import the FluentSQL module and then write your query like this:

.filter(\.$name ~~ term)

如果你更愿意保持现在的样子,那也没关系.

If you would rather leave it the way you have it now, that's fine also.

这篇关于如何在 Vapor 4 (Fluent 4) 中使用用户搜索词防止 SQL 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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