Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Authentication and Security

Authentication with mix phx.gen.auth

Understand what mix phx.gen.auth generates: users, hashed passwords, session tokens, magic links, the UserAuth plug, on_mount hooks and logout handling.

Almost every web application needs to know who is using it. Writing authentication by hand is dangerous: it is easy to store passwords badly, leak whether an email exists, forget to invalidate sessions, or let tokens live forever. Phoenix ships a generator that writes a careful, tested, fully yours authentication system into your project: mix phx.gen.auth. There is no hidden library; every line is in your repository so you can read it and change it.

This lesson explains what the generator creates and why each part exists. The real commands and code are read-only here. The runnable examples are JavaScript stand-ins for the ideas (salted password hashing, session tokens, constant-time comparison) so you can see them work.

Running the generator

Terminal
mix phx.gen.auth Accounts User users
mix deps.get
mix ecto.migrate

The three arguments are the context (Accounts), the schema (User) and the table (users). Options include --hashing-lib argon2 or pbkdf2 (the default is bcrypt, via bcrypt_elixir) and --live or --no-live to choose LiveView or controller-based pages. Phoenix 1.8's generator builds magic-link login (an email link that signs you in, with no password needed) and lets users add a password afterwards in their settings. Older projects, and the --no-live mode, use the classic email-and-password flow. Always read the generator's output notes; they tell you which routes were added.

What you get:

Piece File (typical) Purpose
Schema and token schema accounts/user.ex, accounts/user_token.ex Users, and session and email tokens
Context accounts.ex register_user/1, get_user_by_email_and_password/2, generate_user_session_token/1, ...
Plug and hooks user_auth.ex Loads the current user from the session; protects routes
Pages live/user_live/* Registration, login, confirmation, settings
Migration *_create_users_auth_tables.exs users and users_tokens tables, citext for emails
Tests accounts_test.exs, user_auth_test.exs, ... A thorough test suite you keep

Passwords are never stored

The users table stores hashed_password, never the password. The generated User schema hashes inside a changeset, only if the password is valid:

ELIXIR
def password_changeset(user, attrs, opts \\ []) do
  user
  |> cast(attrs, [:password])
  |> validate_confirmation(:password, message: "does not match password")
  |> validate_password(opts)
end

defp validate_password(changeset, opts) do
  changeset
  |> validate_required([:password])
  |> validate_length(:password, min: 12, max: 72)
  |> maybe_hash_password(opts)
end

defp maybe_hash_password(changeset, opts) do
  hash_password? = Keyword.get(opts, :hash_password, true)
  password = get_change(changeset, :password)

  if hash_password? && password && changeset.valid? do
    changeset
    |> validate_length(:password, max: 72, count: :bytes)
    |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
    |> delete_change(:password)
  else
    changeset
  end
end

Points to notice. The virtual :password field is removed after hashing, so it can never be saved or logged. The 72-byte limit exists because bcrypt ignores everything after 72 bytes. And bcrypt (like argon2) is a deliberately slow, salted hash: each password gets a random salt, so equal passwords produce different hashes, and brute-forcing a stolen database is expensive.

Authentication compares in a way that does not leak timing. The generated code has this shape:

ELIXIR
def get_user_by_email_and_password(email, password) do
  user = Repo.get_by(User, email: email)
  if User.valid_password?(user, password), do: user
end

def valid_password?(%User{hashed_password: hash}, password) when is_binary(hash) and byte_size(password) > 0 do
  Bcrypt.verify_pass(password, hash)
end

def valid_password?(_, _) do
  Bcrypt.no_user_verify()   # burn the same time when the user does not exist
  false
end

Bcrypt.no_user_verify/0 does a fake hash check so that "no such user" takes as long as "wrong password". Without it, an attacker could measure response times to discover which email addresses have accounts.

Node.js Salted hashing and constant-time compare (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.

Session tokens

After a successful login, the app does not put the user id in the cookie. It creates a random session token, saves it in users_tokens, and stores that token in the session. On every request the plug looks the token up:

ELIXIR
def fetch_current_scope_for_user(conn, _opts) do
  {token, conn} = ensure_user_token(conn)
  user = token && Accounts.get_user_by_session_token(token)
  assign(conn, :current_scope, Scope.for_user(user))
end

def log_in_user(conn, user, params \\ %{}) do
  token = Accounts.generate_user_session_token(user)

  conn
  |> renew_session()                      # new session id: stops session fixation
  |> put_token_in_session(token)
  |> maybe_write_remember_me_cookie(token, params)
  |> redirect(to: ~p"/")
end

Storing tokens server-side has big advantages: logging out deletes the token, so a stolen cookie stops working immediately; "log out everywhere" is one DELETE; and tokens carry an age, so old ones are refused. The session cookie itself is signed (and encrypted if you configure it), so the client cannot forge or read a token. renew_session/1 clears the old session when logging in, which prevents session fixation, where an attacker plants a known session id before the victim signs in.

The generated code also stores a live_socket_id in the session, and on logout broadcasts a "disconnect" to that id so open LiveView pages are closed immediately.

Node.js Server-side session tokens (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.

Confirmation, magic-link login and email changes use a second kind of token. It is also random, but the database stores only its SHA-256 hash, and the raw value exists only in the email link. If someone reads your database, they cannot use the stored values to log in. These tokens have short lifetimes (minutes for a login link, a few days for confirmation) and are single use: they are deleted when consumed.

In local development, Swoosh's local adapter lets you open sent emails at /dev/mailbox, so you can click the login link without a mail server. In production, you configure a real adapter in runtime.exs; see Releases and Deployment.

Wiring it into the router

The generator adds a plug to the browser pipeline and two route groups:

ELIXIR
pipeline :browser do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :fetch_live_flash
  plug :protect_from_forgery
  plug :put_secure_browser_headers
  plug :fetch_current_scope_for_user
end

scope "/", MyAppWeb do
  pipe_through [:browser, :require_authenticated_user]

  live_session :require_authenticated_user,
    on_mount: [{MyAppWeb.UserAuth, :require_authenticated}] do
    live "/users/settings", UserLive.Settings, :edit
  end
end

scope "/", MyAppWeb do
  pipe_through [:browser]

  live_session :current_user,
    on_mount: [{MyAppWeb.UserAuth, :mount_current_scope}] do
    live "/users/log-in", UserLive.Login, :new
    post "/users/log-in", UserSessionController, :create
  end
end

Both layers matter. The plug protects the first HTTP request. The on_mount hook protects the connected LiveView, including after push_navigate inside the live session. Every protected LiveView needs both, which the live_session plus pipe_through combination gives you. The next lesson builds on current_scope for authorization: Authorization and Scopes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the generated code call Bcrypt.no_user_verify/0 when a user is not found?

    Equal timing prevents attackers from discovering which emails have accounts.
  2. 2. What does the session cookie contain after login?

    The token is looked up server-side, which lets logout and expiry take effect immediately.
  3. 3. Why does log_in_user call renew_session?

    A new session id means an attacker cannot reuse an id they planted before the victim signed in.
  4. 4. Why do protected LiveViews need both a plug and an on_mount hook?

    The two layers cover the disconnected HTTP render and the WebSocket-connected process.

Summary

  • mix phx.gen.auth writes complete, readable authentication code into your project.
  • Passwords are salted and hashed with a slow algorithm; never stored or logged.
  • Session tokens live in a database table, so logout and expiry work instantly.
  • Email tokens are stored hashed, are single use and short lived.
  • Protect pages with the plug and the on_mount hook together.

Next: Authorization and Scopes