Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to properly prevent SQL injection? #1120

Answered by elprans
2br-2b asked this question in Q&A
Discussion options

Say that I want to insert a user-generated string (for example, a username) into a postgres table. Short of encoding strings in Base64 before I store them, what is the best way to ensure that I am properly protected from SQL injection attacks? Is the built-in variable substitution enough, or does AsyncPG offer a sanitize() function?

I saw this in #275:

asyncpg supports native PostgreSQL syntax for parameter substitution:

v = await conn.fetchrow("SELECT * FROM table WHERE id = 1ドル", my_id)

As long as you pass your parameters like that and never build a query string from user inputs, you should be safe from SQL injection.

but since I am using user input as the parameters, I'm not sure if that was covered by "user inputs". Would this be safe:

v = await conn.fetchrow("SELECT * FROM table WHERE username = 1ドル", user_provided_string)
You must be logged in to vote

Yes, passing data in arguments is always safe.

This, on the other hand is NOT:

v = await conn.fetchrow(f"SELECT * FROM table WHERE username = '{user_provided_string}'")

Replies: 1 comment 3 replies

Comment options

Yes, passing data in arguments is always safe.

This, on the other hand is NOT:

v = await conn.fetchrow(f"SELECT * FROM table WHERE username = '{user_provided_string}'")
You must be logged in to vote
3 replies
Comment options

Thank you for the response earlier! Just to confirm, is this still safe is username could be any Unicode character? Obviously you'd need to sanitize before you displayed the text (especially in a website), but I just want to confirm this

Comment options

Literally any valid Unicode text.

Comment options

Got it! Thank you!

Answer selected by 2br-2b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /