Channel Authentication and Authorization
Secure your Phoenix Channels by verifying user tokens during the join handshake and authorizing access to specific topics.
Why Channels Need Auth
Channels are long-lived WebSocket connections. Without verification, anyone could join a private topic and read or send messages.
Authentication answers who is connecting, while authorization answers what topics they may join.
The Socket Connect Callback
Authentication starts in connect/3 of your UserSocket. It runs once when the WebSocket opens, before any channel is joined.
def connect(%{"token" => token}, socket, _connect_info) do
case verify_token(token) do
{:ok, user_id} -> {:ok, assign(socket, :user_id, user_id)}
:error -> :error
end
endAll lessons in this course
- Introduction to Phoenix Channels
- Broadcasting and Pub/Sub Messaging
- Presence and Live Data Updates
- Channel Authentication and Authorization