如何在 Vapor 4 (Fluent 4) 中使用用户搜索词防止 SQL 注入

编程入门 行业动态 更新时间:2024-10-27 03:36:45
本文介绍了如何在 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 注入

本文发布于:2023-10-22 23:56:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户   搜索词   如何在   Fluent   Vapor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!