Learn how to implement authentication in Phoenix using the phx.gen.auth generator for full control and customization.
Phoenix authentication uses a code generator, not a package
- Run
mix phx.gen.auth
to scaffold everything you need (schema, DB migrations, context, routes, UI)
- Code is yours to customize, unlike black-box packages
Why use a generator?
- Full code visibility and control (inspired by experiences with Devise in Rails)
- Easily tweak validations, confirmations, or token logic without magic
Command
mix phx.gen.auth Accounts User users
- “Accounts” is the context, “User” is the schema, “users” is the DB table
Includes
- User schema: email, password (with
:redact
for security), confirmation fields, etc.
- Password hashing: Uses
bcrypt_elixir
package (with test/dev/production config options)
- Database-backed sessions: Tables for users and user tokens support secure multi-device sessions and password resets
- UserNotifier: Ready for real email provider integration using Swoosh, but you must configure real SMTP/sending in production
- Plug-based user authentication: Robust pipeline for log in, log out, new password, and confirmation, with easy extension
Customization
- Code is heavily commented for straightforward config (such as stricter password rules)
- Email uniqueness and security is handled regardless of DB (e.g., case insensitivity for SQLite/Postgres)
UI & Testing
- Generates UI using LiveView for registration/login flows (but can fallback to controller-based UI)
- Includes test helpers for easily managing authenticated sessions in tests
- Dev mailbox at
/dev/mailbox
lets you view confirmation/reset emails in dev mode
- You can require email confirmation before login by tweaking
require_authenticated_user
- Sessions are safer than client-only cookies—reset all sessions when password changes
Summary
Phoenix’s gen.auth generator gives you a modern, production-ready, fully customizable authentication system out of the box, prioritizing visibility, safety, and adaptability to your app’s needs. Unlike plugin-style packages, you control and update every part of your auth logic.