Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Authentication and Security

Web Security in Phoenix

Secure a Phoenix app: CSRF tokens, automatic XSS escaping and raw/1 risks, SQL injection and Ecto fragments, security headers, CSP, check_origin, HTTPS and rate limiting.

Phoenix is secure by default in many ways: templates escape output, Ecto uses parameterized queries, forms carry CSRF tokens, and sessions are signed. That is a strong start, but a framework cannot protect you from code that switches those protections off. This lesson walks through the common attacks, shows what Phoenix does about each one, and names the specific mistakes that undo it.

Real code is read-only. The runnable examples model the mechanisms in JavaScript so you can see why they work.

Cross-site request forgery (CSRF)

If you are signed in to your bank in one tab and visit a malicious page in another, that page can make your browser send a request to the bank, and the browser will attach your session cookie. The bank cannot tell your click from the attacker's forged form. The defence is a secret CSRF token that the attacker's page cannot read.

In the :browser pipeline, plug :protect_from_forgery rejects POST, PUT, PATCH and DELETE requests that do not carry a valid token with a Plug.CSRFProtection.InvalidCSRFTokenError (a 403). The generated layout includes the token in a <meta> tag, and the form helpers add a hidden field automatically:

HTML
<meta name="csrf-token" content={get_csrf_token()} />

<.form for={@form} action={~p"/session"}>   <%!-- hidden _csrf_token is added for you --%>

LiveView reads the meta tag and sends the token when opening its socket (params: {_csrf_token: csrfToken} in app.js). Rules to follow:

  • Keep protect_from_forgery in every browser pipeline.
  • Never perform state changes with GET. The check does not apply to them.
  • API pipelines that use bearer tokens in a header (not cookies) do not need CSRF protection, but must not rely on cookies for authentication.
  • Combine it with SameSite=Lax session cookies, which Phoenix sets by default.
Node.js Why a forged request has no token (stand-in)

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 node:readline or process.stdin), it gets the next line from this box.

Cross-site scripting (XSS)

XSS happens when attacker-controlled text is placed into a page as HTML. If a comment contains <script>steal(document.cookie)</script> and you print it unescaped, it runs in every visitor's browser. HEEx escapes everything interpolated with {...} or <%= %> by default, turning < into &lt;:

HTML
<p>{@comment.body}</p>   <%!-- safe: <script> becomes visible text --%>

The danger is turning that off. These are the typical mistakes:

ELIXIR
# DANGEROUS: marks user text as already-safe HTML
{raw(@comment.body)}
Phoenix.HTML.raw("<b>" <> user_input <> "</b>")

# DANGEROUS: user data inside a script or an attribute that runs code
<a href={@user.website}>site</a>        # a "javascript:alert(1)" URL can run code

Guidelines: do not use raw/1 with user data. If you must show user-written rich text, run it through a sanitizer library (for example html_sanitize_ex) with an allow-list of tags first. Validate URLs from users to allow only http and https schemes. Pass data to JavaScript through data-* attributes (Phoenix encodes them) rather than building script text by string concatenation.

Node.js Escaping output (stand-in)

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 node:readline or process.stdin), it gets the next line from this box.

SQL injection

Ecto sends values separately from the SQL text, so a query like this is safe even if name contains quotes and SQL keywords:

ELIXIR
from u in User, where: u.name == ^name       # the ^ pins a parameter

The mistakes are all about building SQL as a string:

ELIXIR
# DANGEROUS
Repo.query!("SELECT * FROM users WHERE name = '#{name}'")
from u in User, where: fragment("name = '#{name}'")

# SAFE: placeholders
Repo.query!("SELECT * FROM users WHERE name = $1", [name])
from u in User, where: fragment("lower(name) = lower(?)", ^name)

Never interpolate request data into a fragment string or a raw query. Also never turn request strings into atoms with String.to_atom/1: atoms are never garbage-collected, so an attacker can exhaust the VM. Use String.to_existing_atom/1 or match the value against an allow-list.

Mass assignment

cast/3 lists the fields a changeset accepts from params. If you cast :role in a user-facing changeset, an attacker can add user[role]=admin to a form. Cast only the fields a given form is allowed to change, and use a separate changeset for admin-only fields. Ownership ids come from the scope, never from params.

Secure headers, HTTPS and origins

plug :put_secure_browser_headers adds x-frame-options, x-content-type-options, a referrer-policy and a default content-security-policy (a restrictive base-uri 'self'; frame-ancestors 'self'). You can tighten the CSP, for example to forbid inline scripts:

ELIXIR
plug :put_secure_browser_headers, %{
  "content-security-policy" =>
    "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
}

A strong CSP limits the damage of any XSS you missed. In production also set:

ELIXIR
# config/runtime.exs or prod.exs
config :my_app, MyAppWeb.Endpoint,
  force_ssl: [hsts: true, rewrite_on: [:x_forwarded_proto]],
  check_origin: ["https://myapp.example.com"]

force_ssl redirects HTTP to HTTPS and sends the HSTS header (use rewrite_on behind a load balancer that terminates TLS). check_origin makes the WebSocket endpoint refuse connections from other websites, which protects channels and LiveView from cross-site WebSocket hijacking. Never set it to false in production.

Rate limiting and secrets

Login forms, password resets and magic-link requests must be rate limited or attackers can guess passwords or spam your users. Phoenix has no built-in limiter; the common choices are the Hammer library or a small plug backed by ETS. The idea is a bucket per key (IP or email) that refills over time.

Node.js A token-bucket rate limiter (stand-in)

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 node:readline or process.stdin), it gets the next line from this box.

Secrets such as secret_key_base, database URLs and API keys belong in environment variables read by config/runtime.exs, never in the repository. Rotating secret_key_base invalidates all signed sessions, which is how you force everyone to sign in again after a leak. Run mix sobelow (a security-focused static analyzer for Phoenix) and mix deps.audit in CI to catch known weaknesses in your code and dependencies; the Elixir security lesson has more general advice.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does protect_from_forgery protect against?

    It requires a secret token on state-changing requests that an attacker's page cannot read.
  2. 2. Which of these is the most dangerous with user data?

    raw/1 disables escaping, so injected script tags are rendered as HTML and run.
  3. 3. How do you safely use a value in an Ecto fragment?

    Parameters are sent separately from the SQL text, so the value can never become SQL.
  4. 4. What does check_origin do on the Endpoint?

    It blocks cross-site WebSocket hijacking by comparing the Origin header with allowed hosts.

Summary

  • Keep protect_from_forgery on every browser pipeline and never change state with GET.
  • HEEx escapes output; avoid raw/1 with user data and validate user-supplied URLs.
  • Ecto parameterizes queries; never build SQL or fragment strings with interpolation.
  • Cast only the fields a form may change; take ownership from the scope.
  • Set secure headers and a CSP, force_ssl and check_origin in production, and rate limit sensitive endpoints.
  • Keep secrets in runtime configuration and run sobelow and dependency audits in CI.

Next: Testing Controllers and Contexts