These four terms are essential introductory material for web security: do not execute user input as code (injection, XSS), do not let others forge requests as the user (CSRF), and do not casually open up cross-site access (CORS).
1. SQL injection
How it works: user input is concatenated into a SQL statement, and special characters in the input change the statement’s meaning.
Defense: parameterized queries (pass data and the statement separately). ORMs are parameterized by default; see ORM. Giving the database account only the permissions it needs also limits damage.
// db.Database.ExecuteSqlRaw($"SELECT * FROM Users WHERE Name = '{name}'");
// Safe: EF Core FromSql turns the interpolation into a parameter
var users =awaitdb.Users
.FromSql($"SELECT * FROM Users WHERE Name = {name}")
.ToListAsync();
# Dangerous: cursor.execute(f"SELECT * FROM users WHERE name = '{name}'")
# Safe: placeholders; the driver handles parameters
cursor.execute("SELECT * FROM users WHERE name = %s",[name])
# Note: placeholders differ by driver (%s, ?, :name); follow the driver docs
2. XSS (cross-site scripting)
How it works: content submitted by a user contains a script; the page echoes it as-is, it runs in other users’ browsers, and login credentials can be stolen.
Defense:
Escape on output: turn < into <. Razor, Django templates, and React/Vue escape by default—do not casually use @Html.Raw, |safe, dangerouslySetInnerHTML, or v-html.
When rich text is required, sanitize with an allowlist library.
Set Cookie HttpOnly, and configure a Content-Security-Policy response header as a second line of defense.
3. CSRF (cross-site request forgery)
How it works: browsers automatically attach cookies, so a malicious site can make your browser send requests to the target site.
Defense:
Set Cookie SameSite=Lax or Strict.
For requests that change data, use a CSRF token (the server issues a random value that must be sent back on submit).
Never use GET for data-changing operations.
If an API uses only a Bearer token in the request header (and does not rely on cookies), CSRF risk is lower; see the trade-offs in JWT and sessions.
Django enables CsrfViewMiddleware by default; ASP.NET Core has Antiforgery, wired into Razor Pages/MVC forms by default, while Minimal APIs need the matching middleware enabled yourself.
🔀 CSRF: using your browser to "click the button" for you
Your browser
Bank site
Malicious site
1You are signed in; the browser holds a Cookie
2You also open a malicious page
3The page silently makes the browser send a transfer request
4The request automatically includes the Cookie
5Missing CSRF token or SameSite: reject
Defense: set SameSite on cookies, and require a CSRF token on mutating requests.
4. CORS (cross-origin resource sharing)
To be clear: CORS is not an attack; it is a browser protection. By default, page scripts cannot read responses from APIs on a different origin. The server declares “which origins are allowed” via response headers; a misconfigured CORS policy is what becomes a vulnerability.
Defense:
List only explicit frontend origin allowlists.
Do not use * (wildcard) or reflect the request Origin as-is on cookie-bearing endpoints.
CORS constrains browsers only; it does not replace authentication and authorization. Scripts and curl can still call your API directly.
builder.Services.AddCors(o =>o.AddPolicy("web", p =>
p.WithOrigins("https://app.example.com")
.WithMethods("GET", "POST")
.AllowAnyHeader()));
app.UseCors("web");
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],# do not use "*"
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
Component comparison
Built-in framework protections
Built into the frameworkOpsLow
Use the framework's own defenses directly: parameterized queries stop SQL injection, automatic template escaping stops XSS, and anti-forgery tokens stop CSRF.
Best forThe starting point of every project; it must be used correctly first.
Avoid whenThere is no case for not choosing it; but do not rely on it alone, and combine it with other measures.
Pros
Nothing extra to deploy, and the defaults already block most common attacks
Fixes arrive with the framework upgrade, so you do not track them separately
The cost is the lowest, and it is the base for the other security measures
Cons
Hand-built SQL strings or raw HTML output will bypass the protection
It only protects the code that actually runs, and it cannot stop mass scanning
Newcomers can turn the protection off by accident, so they need to understand why it is there
Security response headers middleware
Self-hosted open sourceOpen sourceOpsLow
Automatically add a set of "security hint headers" (such as Content Security Policy, CSP) to every response, giving the browser an extra layer of protection.
Best forProjects with a web frontend that want an extra safeguard against XSS.
Avoid whenPure backend APIs with no web output, where the benefit is limited.
Pros
CSP can restrict malicious script execution when an XSS hole exists, serving as a second line of defense
A few lines of configuration take effect site-wide
No extra runtime service to maintain
Cons
A strict CSP may break third-party and inline scripts and needs repeated tuning
Only works in browsers, and cannot protect against flaws in the API itself
Bad configuration can produce blank pages, so verify in a test environment before release
Dependency vulnerability scanning
Self-hosted open sourceOpen sourceOpsLow
Automatically check whether the third-party libraries your project uses have publicly known security vulnerabilities, and prompt you to upgrade when they do.
Best forAny project using third-party libraries; recommended as a routine process.
Avoid whenIt is never unsuitable, but do not treat it as the whole of your security measures.
Pros
Known vulnerabilities in outdated third-party libraries can be found early
Once it is in continuous integration, every commit is checked automatically
Most tools are free, and adding them to the pipeline does not cost much
Cons
It only finds vulnerabilities that have already been published, not bugs in code you wrote
There are quite a few alerts, and a person must judge which ones really apply
Upgrading a dependency may be incompatible, so leave time to test
Checklist
All database queries are parameterized; no string-concatenated SQL
Page output escapes by default; no casual use of “raw output” switches
A CSP response header is present
Cookies set HttpOnly, Secure, and SameSite
Mutating requests have CSRF protection and do not use GET
CORS uses an explicit allowlist; no * paired with credentials