How to prevent SQL Injections with User-Search-Terms in Vapor 4 (Fluent 4)

不想你离开。 提交于 2021-02-10 12:48:45

问题


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)

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).

My Question:
Is SQL Injection (or other attacks) possible and if so, how can I prevent it (please provide a code example)?


回答1:


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 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 = ?

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.

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.



来源:https://stackoverflow.com/questions/63634126/how-to-prevent-sql-injections-with-user-search-terms-in-vapor-4-fluent-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!