0Pricing
Elixir & Phoenix: Scalable Backend Development · Lesson

Channel Authentication and Authorization

Secure your Phoenix Channels by verifying user tokens during the join handshake and authorizing access to specific topics.

Channel Authentication and Authorization is a free Elixir & Phoenix: Scalable Backend Development lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Elixir & Phoenix: Scalable Backend Development learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
end

Generating a Token

Phoenix ships Phoenix.Token for signing short-lived tokens. The server signs the user id and the client passes it back when connecting.

token = Phoenix.Token.sign(MyAppWeb.Endpoint, "user socket", user.id)

Verifying a Token

On connect, verify the token with the same salt. The max_age option rejects expired tokens.

Phoenix.Token.verify(MyAppWeb.Endpoint, "user socket", token, max_age: 86400)

Rejecting Unauthorized Connections

Returning :error (or {:error, reason}) from connect/3 closes the socket immediately. The client never reaches any channel.

def connect(_params, _socket, _info), do: :error

Assigning the Current User

After verifying, store the identity on the socket with assign/3. Every channel on this socket can then read socket.assigns.user_id.

{:ok, assign(socket, :user_id, user_id)}

Authorizing Channel Joins

Authorization happens in join/3. Compare the requested topic against the authenticated user before allowing the join.

def join("room:" <> room_id, _params, socket) do
  if authorized?(socket.assigns.user_id, room_id) do
    {:ok, socket}
  else
    {:error, %{reason: "unauthorized"}}
  end
end

Scoping Private Topics

A common pattern uses the user id inside the topic name, like user:42. Reject the join if the topic id does not match the connected user.

def join("user:" <> id, _params, socket) do
  if id == to_string(socket.assigns.user_id) do
    {:ok, socket}
  else
    {:error, %{reason: "forbidden"}}
  end
end

Client-Side Token Passing

The JavaScript client sends the token as a connection param. The server reads it in connect/3.

let socket = new Socket('/socket', { params: { token: window.userToken } })
socket.connect()

Handling Token Expiry

Tokens are short-lived on purpose. When a token expires the socket disconnects; the client should fetch a fresh token and reconnect.

  • Keep max_age short for sensitive apps
  • Refresh tokens before they expire
  • Handle the socket onError event to reconnect

Security Best Practices

Strengthen channel security:

  • Never trust client-supplied user ids — derive identity from the token
  • Authorize every topic in join/3
  • Validate incoming payloads in handle_in/3
  • Use HTTPS/WSS so tokens travel encrypted

Quick Check

Test your channel security knowledge.

Recap

You secured Phoenix Channels end to end:

  • Authenticate the socket in connect/3 using Phoenix.Token
  • Assign the verified user onto the socket
  • Authorize each topic in join/3
  • Reject expired tokens and reconnect with fresh ones

Proper auth keeps private real-time data safe.

Frequently asked questions

Is the “Channel Authentication and Authorization” lesson free?

Yes — the full text of “Channel Authentication and Authorization” is free to read here on the web, and the Elixir & Phoenix: Scalable Backend Development course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Elixir & Phoenix: Scalable Backend Development course, upgrade to CoddyKit PRO.

What will I learn in “Channel Authentication and Authorization”?

Secure your Phoenix Channels by verifying user tokens during the join handshake and authorizing access to specific topics. You practise Elixir & Phoenix: Scalable Backend Development with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Elixir & Phoenix: Scalable Backend Development?

No prior experience is required. Elixir & Phoenix: Scalable Backend Development on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Channel Authentication and Authorization” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Elixir & Phoenix: Scalable Backend Development lesson?

Yes. Every Elixir & Phoenix: Scalable Backend Development lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Introduction to Phoenix Channels
  2. Broadcasting and Pub/Sub Messaging
  3. Presence and Live Data Updates
  4. Channel Authentication and Authorization
← Back to Elixir & Phoenix: Scalable Backend Development