SQL injection vs XSS vs CSRF: the classic web attacks explained
These three attacks have been around for decades, and they still show up regularly. Each exploits a different trust relationship.
SQL injection: the app trusts user input in database queries
If an app builds a query by concatenating user input, an attacker can supply input that changes the query itself, reading or modifying data they shouldn't.
Defence: use parameterised queries or prepared statements so input is always treated as data. ORMs help, but raw query escapes in ORMs can reintroduce the problem.
Cross-site scripting (XSS): the browser trusts content from the site
An attacker gets their script into a page others view, for example via a comment field. The script runs with the victim's session and can steal data or take actions.
Defence: escape output based on context (HTML, attributes, JavaScript, URLs). Modern frameworks escape by default; be careful with features that insert raw HTML. A Content Security Policy adds a second layer.
Cross-site request forgery (CSRF): the site trusts the browser's cookies
A malicious page causes the victim's browser to send a request to another site where they're logged in, and the browser attaches their cookies automatically.
Defence: SameSite cookie settings, anti-CSRF tokens, and requiring non-GET methods for state changes.
The common lesson: never trust input, and keep code and data separate.
Which of these have you encountered in real code? Do modern frameworks make any of them effectively solved?
Comments · 3
Parameterized queries stopped SQL injection for me when I was learning. Once you see why string concatenation is dangerous, you never go back.
Easy way to remember: SQLi attacks your database, XSS attacks other users' browsers, CSRF abuses a logged-in user's session.
Do modern frameworks mostly protect against CSRF by default, or do you still need to opt in to tokens?