Prevent SQL Injection in Dynamic column names Prevent SQL Injection in Dynamic column names postgresql postgresql

Prevent SQL Injection in Dynamic column names


You can get the column names from the database and compare to check the user has entered a valid column name.


SQL Injection happens because user entered data is used in a dynamic query, without paramerterizing it. Unfortunately, in your case the user entered data can not be paramertized, the solution is to not let the user enter that data.

A possible workaround would be to use a whitelist (not BLACKlist) of acceptable characters. But really, you should see about obtaining a list of fieldNames and verifying the users input (and then use YOUR version of the string, not the one that came from the user).

User entered data is always suspect, and should be avoided if at all possible.


One thing you could do is go ahead and create your dynamic query but put something like this as a prefix:

"IF EXISTS(SELECT * FROM sys.columns where object_id=OBJECT_ID('mytable') and name = @dynamicName)    SELECT * FROM mytable WHERE [" + dynamicName + "] = 'Whatever your test is.'"

Yeah, it makes the query a little more expensive, but it is protected against injection.