问题
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