LiveView begins its life-cycle as a regular HTTP request, then establishes a stateful connection. Both phases receive client data via parameters and session, requiring careful security considerations.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/phoenixframework/phoenix_live_view/llms.txt
Use this file to discover all available pages before exploring further.
Authentication vs Authorization
Authentication identifies who a user is (e.g., by email/password or OAuth). Authorization determines what a user can access or do in the system.Authentication Flow
Phoenix and tools like
mix phx.gen.auth can generate the building blocks of an authentication system for you.LiveView Security Flow
LiveViews share authentication logic with regular requests through plugs:- HTTP Request → Endpoint → Router → Plugs → LiveView HTTP mount
- WebSocket Connection → LiveView connected mount
Using live_session
The Phoenix.LiveView.Router.live_session/2 is the primary mechanism for grouping LiveViews with shared authentication/authorization requirements.
Basic Usage
Why live_session?
- Navigation within a session: Skip regular HTTP requests and plug pipeline
- Navigation across sessions: Go through the router and plugs again
- Security boundary: Different authentication requirements
- Layout changes: Different root layouts for different sections
Use
live_session to enforce different authentication requirements (like user vs admin), not just for minor authorization differences.The on_mount Hook
The on_mount hook allows you to run authentication/authorization logic on every LiveView mount.
Implementing a LiveAuth Hook
Using the Hook
You can use the hook in three ways: 1. In the router (recommended):Mounting Considerations
Themount/3 callback is invoked both on initial HTTP mount and when LiveView connects. Any authorization performed during mount covers all scenarios.
Example: User Authentication
Example: Resource Authorization
If the user doesn’t have access to the organization,
Repo.get! raises Ecto.NoResultsError, which is converted to a 404 page.Event Authorization
Every user action must be verified on the server, regardless of UI state.Why Event Authorization?
Even if you hide the “Delete” button in the UI, a savvy user can directly send a delete event to the server. You must always verify permissions on the server.Example: Delete Authorization
Disconnecting Live Users
Because LiveView maintains a permanent connection, changes like logout or account revocation won’t reflect until the user reloads the page.Using live_socket_id
Set a live_socket_id in the session when logging in:
If you use
mix phx.gen.auth, lines for this are already present in the generated code, using a user_token instead of user_id.When to Disconnect
- User logs out
- User account is deleted
- User permissions are revoked
- User password is changed
- Session is invalidated
How It Works
Shared with Phoenix Channels
This is the same mechanism provided byPhoenix.Channel, so it works for both LiveViews and Channels.
Complete Example
Router
UserLiveAuth Hook
AdminLiveAuth Hook
Best Practices
- Use
live_sessionfor authentication boundaries: Different user types (user vs admin) should have separate live sessions - Implement
on_mounthooks: Centralize authentication logic in reusable hooks - Verify in events: Always check permissions in
handle_eventcallbacks - Set
live_socket_id: Enable disconnecting users when their session is invalidated - Use
assign_new: Avoid redundant database queries across parent-child LiveViews - Match on plug logic: Ensure LiveView auth matches your plug auth logic
- Test auth paths: Test both authenticated and unauthenticated scenarios
- Use context functions: Keep authorization logic in your context modules
Security Checklist
- Authentication logic exists in both plugs and
on_mount -
live_sessiongroups separate auth requirements -
on_mounthooks validate user session - Resource access is verified in
mount/3 - Action permissions are checked in
handle_event/3 -
live_socket_idis set for disconnecting users - CSRF tokens are validated (automatic in Phoenix)
- Session data is signed and encrypted (automatic in Phoenix)
- Authorization tests cover all scenarios
Summary
The important concepts:live_session: Draw boundaries between groups of LiveViews with different authentication requirements- Authentication in mount: Shared between regular web requests (via plugs) and LiveViews (via
on_mount) - Authorization in mount: Check if user can see this page
- Authorization in events: Check if user can perform this action
- Disconnect mechanism: Use
live_socket_idto disconnect users when sessions are invalidated