Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 72 ยท Authentication and Security

Web Security Essentials

Learn the web attacks every Flask developer must stop. Covers XSS and autoescape, SQL injection, CSRF tokens, secure cookies, security headers, CORS and open redirects.

Once your app has users, data and forms, it has attackers too. The good news is that a small set of attacks causes most real-world breaches, and Flask plus a few habits protects you from nearly all of them. You do not need to be a security expert. You need to know what each attack looks like, which default protects you, and which mistake switches the protection off.

This lesson tours the essentials: XSS (injected scripts), SQL injection, CSRF (forged requests), cookie flags, security headers, CORS, and open redirects. Each section shows the attack running against deliberately weak code, then the fix. Everything runs inside the in-process test client, so there is no server to attack, only code to understand. It builds on the login system and authorization lessons.

XSS: cross-site scripting

Cross-site scripting happens when your page prints user-supplied text as HTML. If a comment contains <script>steal()</script> and you output it unchanged, every visitor's browser runs the attacker's code with your site's privileges. It could read the page, send requests as the user, or show a fake login form.

Flask's defense is autoescaping. Jinja templates loaded from .html files (and strings passed to render_template_string) escape <, >, & and quotes by default, turning them into harmless entities. You only lose that protection when you opt out:

  • the |safe filter,
  • wrapping text in Markup(...),
  • {% autoescape false %},
  • building HTML with f-strings and returning it directly.
Python Autoescape versus |safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fifth case is subtle: autoescape does not stop a value containing a space from adding another attribute when you forget the quotes. Always write value="{{ v }}".

Rules for staying safe:

  • Leave autoescape on and never apply |safe to anything a user can influence. If you must allow formatting (Markdown, rich text), convert and sanitize it with a maintained library such as nh3 or bleach, then mark only the sanitized result as safe.
  • Never build HTML with string concatenation. Use templates.
  • Do not put user data inside <script> blocks or href="javascript:...". Use {{ data|tojson }} to embed values in JavaScript, because it escapes correctly for that context.
  • Add a Content Security Policy header (below) as a second layer.

SQL injection

SQL injection happens when user input is pasted into a SQL string. A visitor who types ' OR '1'='1 as a name changes the meaning of your query. The fix is to keep data and code apart with parameterized queries: you write the SQL with placeholders and pass values separately, so the database never mistakes a value for SQL.

Python Injection and the parameterized fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The unsafe query returned every row for the attack string, while the safe one correctly returned nothing. The second attack uses --, the SQL comment marker, to throw away the rest of the query, including the secret check, so the "login" succeeds with a wrong secret. Some database drivers also allow several statements per call, which lets an attacker append things like DROP TABLE. Parameters apply to values only. Table and column names cannot be bound, so if they must vary, choose from a fixed allowlist in your code. ORMs like SQLAlchemy parameterize for you, but raw text() queries built with f-strings are just as dangerous. See also Using sqlite3 with Flask.

CSRF: cross-site request forgery

Browsers attach your cookies to every request to your site, even when the request is triggered by another site. Suppose you are logged in to a bank, then visit a malicious page that contains a hidden form posting to bank.example/transfer. Your browser sends the session cookie, and the bank sees a legitimate, authenticated request. That is CSRF.

The standard defense is a CSRF token: a random value generated per session, placed in every form, and checked on every state-changing request (POST, PUT, PATCH, DELETE). The attacker's page can make your browser send the cookie but cannot read the token from your site, so it cannot include the right value.

sequenceDiagram
    participant U as User's browser
    participant S as Your site
    participant E as Evil page
    U->>S: GET /form
    S-->>U: HTML form with hidden csrf_token + session cookie
    U->>S: POST /transfer (cookie + correct token)
    S-->>U: 200 accepted
    E->>S: POST /transfer from the victim's browser (cookie, no token)
    S-->>E: 400 rejected

The forged request carries the cookie automatically, but it cannot know the token.

In real projects, use Flask-WTF's CSRFProtect (see Validation with WTForms), which does this for every form. The small version below shows what it does underneath.

Python A hand-made CSRF token check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details matter. hmac.compare_digest compares in constant time, so the check does not leak how many characters matched. And GET requests must never change data, because the token check only guards unsafe methods. Modern browsers also help: set SESSION_COOKIE_SAMESITE = "Lax" (see the next section) so cookies are not sent on cross-site POSTs. Treat that as a second layer, not a replacement for tokens. JSON APIs that authenticate with an Authorization header instead of cookies are not vulnerable to CSRF, which is one reason token-based APIs are popular.

The session cookie carries your users' logins, so its flags matter. Flask exposes them as config values:

Setting Effect
SESSION_COOKIE_HTTPONLY JavaScript cannot read the cookie (default True)
SESSION_COOKIE_SECURE Browser sends it only over HTTPS (default False; turn on in production)
SESSION_COOKIE_SAMESITE "Lax" or "Strict" limits cross-site sending (default None; use "Lax")
PERMANENT_SESSION_LIFETIME How long permanent sessions last

The SECRET_KEY must be long, random and never committed to source control (see Configuration).

Security headers and CORS

Browsers support response headers that switch on extra protection. Because every response should carry them, an after_request hook (hooks) is the natural place. Useful ones:

  • X-Content-Type-Options: nosniff stops the browser from guessing a file's type and running an upload as a script.
  • X-Frame-Options: DENY (or CSP frame-ancestors) prevents other sites from embedding your pages in a frame to trick clicks (clickjacking).
  • Content-Security-Policy lists where scripts, styles and images may come from. A strict policy turns many XSS bugs into harmless errors.
  • Referrer-Policy limits how much of your URLs is leaked to other sites.
  • Strict-Transport-Security (HSTS) tells browsers to use HTTPS only. Send it over HTTPS only.

CORS (cross-origin resource sharing) is related but different. Browsers block JavaScript on https://a.example from reading responses from https://b.example unless b opts in with an Access-Control-Allow-Origin header. It protects users, not your server, and it does not stop requests from arriving. Never answer * for endpoints that use cookies, and never echo back whatever Origin header you receive without checking it against an allowlist. The extension flask-cors does this well in production.

Python Cookie flags, security headers and a CORS allowlist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In production add Strict-Transport-Security and send it only on HTTPS. A tight CSP can break inline scripts and styles, so test it. Start with the policy above and loosen only what you need.

Flask-Talisman: all the headers in one call

Writing the after_request hook by hand is fine for learning. In a real project the extension Flask-Talisman sets a safe set of headers for you and can redirect HTTP to HTTPS:

TEXT
pip install flask-talisman
Python Flask-Talisman sets the security headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

By default Talisman sends X-Frame-Options: SAMEORIGIN, X-Content-Type-Options: nosniff, a Referrer-Policy, HSTS (over HTTPS only) and a restrictive Content-Security-Policy. Remember three rules:

  • A strict CSP blocks inline scripts and styles. Either move them into files, or let Talisman add a per-request nonce (content_security_policy_nonce_in=["script-src"]) and write <script nonce="{{ csp_nonce() }}">.
  • force_https=True is for production. Locally, or behind a proxy that terminates TLS, turn it off or configure ProxyFix first (Deployment), otherwise you get redirect loops.
  • Headers are defence in depth. They do not replace escaping output, CSRF tokens and parameterized queries.

Flask-CORS in depth

Writing CORS headers by hand, as above, teaches the mechanism. In a real project use the Flask-CORS extension (pip install flask-cors), which handles the details you would otherwise get wrong: preflight requests, matching several origins, the Vary: Origin header and credentials.

What the browser does

For a "simple" cross-origin request (a GET, or a POST with a form content type) the browser sends it and checks the response headers. For anything else (a DELETE, a JSON Content-Type, an Authorization header) it first sends a preflight: an OPTIONS request that asks "may I?". Your server answers with the allowed origins, methods and headers, and only then does the browser send the real request.

sequenceDiagram
    participant B as Browser at app.example.com
    participant S as Your Flask API
    B->>S: OPTIONS /api/profile<br/>Origin, Access-Control-Request-Method: DELETE
    S-->>B: 200 + Allow-Origin, Allow-Methods, Allow-Headers, Max-Age
    B->>S: DELETE /api/profile (real request)
    S-->>B: 200 + Allow-Origin

A preflight is an extra round trip; Max-Age lets the browser cache the answer.

Configuring it

CORS(app, ...) applies rules to URL patterns through resources. Each pattern (a regular expression) gets its own options:

  • origins: a string, a list, or regular expressions. "*" means any origin.
  • methods and allow_headers: what the preflight announces.
  • supports_credentials: allow cookies and Authorization headers on cross-origin requests. It adds Access-Control-Allow-Credentials: true.
  • max_age: seconds the browser may cache the preflight result.

For one route, the @cross_origin(...) decorator takes the same options.

Python Flask-CORS: resources, origins, preflight, credentials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the output line by line:

  • An origin on the list (or matching a regular expression) gets Allow-Origin set to that exact origin plus Allow-Credentials. An unlisted origin gets no CORS headers at all, so the browser blocks the page from reading the answer. The request itself still reached your server and ran, which is why CORS never replaces authentication.
  • /private matches no pattern, so it sends no CORS headers: the safe default is "closed".
  • The first preflight announces DELETE, GET, POST, the allowed headers and Max-Age: 600. The second asks for PATCH, which is not allowed, so the response lacks Allow-Methods and the browser refuses to send the real request.

Rules that prevent mistakes

  • Never combine origins="*" with supports_credentials=True. Browsers reject a wildcard on credentialed requests, and echoing every origin back instead would let any website act as your logged-in user. List real origins.
  • Prefer an allowlist from configuration (origins=app.config["CORS_ORIGINS"]), different in development and production.
  • Cover only what needs it, such as r"/api/*", not the whole app.
  • If a cross-origin request fails with a CORS error and your Flask log shows a 401 or an exception, fix that first. Error responses without CORS headers look like CORS problems in the browser console.
  • For cookies across sites also set SameSite=None; Secure on the session cookie, which has its own security cost; same-site subdomains usually work with Lax.
  • Behind a proxy, check where the CORS headers are added: adding them in both nginx and Flask produces a duplicated Access-Control-Allow-Origin, which browsers reject.

If your API and your front end share one origin (for example /api behind the same host), you need no CORS at all. See token authentication for the headers a cross-origin client will send.

Open redirects

Views such as login accept a next URL and redirect to it. If you follow any value, an attacker can craft https://yoursite.example/login?next=https://evil.example and your own trusted domain bounces people to a phishing page. The fix is to allow only URLs that stay on your host. Comparing the target's host with the current request's host works for both relative and absolute URLs:

Python A host-aware safe redirect check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Relative paths and URLs on your own host (the test client's host is localhost) pass; everything else falls back to the home page.

A short checklist

  • Keep autoescape on; use |safe only on text you generated, and sanitize rich text.
  • Use parameterized queries or an ORM, never f-strings in SQL.
  • Protect every state-changing form with a CSRF token; never change data on GET.
  • Set SECURE, HTTPONLY and SAMESITE on the session cookie, with a strong secret key.
  • Send security headers and a Content Security Policy.
  • Use a CORS allowlist, never * with credentials.
  • Validate redirect targets and file uploads (see File Uploads).
  • Hash passwords (Password Hashing), serve everything over HTTPS, keep DEBUG off in production, and update dependencies.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which template construct disables Jinja's autoescaping for a value?

    The safe filter marks text as already-safe HTML, so it is printed unescaped. Never use it on user-controlled input.
  2. 2. What is the correct defense against SQL injection?

    Parameterized queries keep values separate from SQL code, so the database cannot interpret input as part of the statement.
  3. 3. Why can an attacker's page make your browser send a forged POST to your site, and what stops it?

    Cookies travel with any request to your domain. The attacker cannot read the token embedded in your pages, so a forged request fails the check.
  4. 4. Which cookie setting prevents JavaScript from reading the session cookie?

    HttpOnly hides the cookie from document.cookie, which limits what an XSS bug can steal. Secure limits it to HTTPS and SameSite limits cross-site sending.
  5. 5. What is wrong with answering every CORS request with Access-Control-Allow-Origin set to the request's own Origin value?

    Echoing the origin without checking an allowlist grants every site access. Compare the origin with a fixed set of trusted origins.

Summary

  • Autoescape defends against XSS; do not bypass it with |safe, Markup or f-string HTML, and quote attribute values.
  • Parameterized queries stop SQL injection; table and column names must come from an allowlist.
  • CSRF tokens (Flask-WTF's CSRFProtect in real apps) protect state-changing requests; GET must never change data.
  • Set SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY and SESSION_COOKIE_SAMESITE, and keep SECRET_KEY long, random and secret.
  • Add security headers in an after_request hook, including a Content Security Policy.
  • CORS is an opt-in to cross-origin reading: use an allowlist, never * with cookies. In real projects use Flask-CORS (resources, origins, preflight handling) rather than hand-written headers.
  • Redirect only to targets on your own host.

Next: Building JSON APIs, where Flask serves data instead of pages.