0Pricing
Elixir & Phoenix: Scalable Backend Development · 课时

频道认证与授权

在加入握手期间验证用户令牌,并授权用户访问特定主题,从而保护 Phoenix Channels。

频道认证与授权 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Elixir & Phoenix: Scalable Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「频道认证与授权」课时是免费的吗?

是的 — 「频道认证与授权」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。

「频道认证与授权」这节课中我会学到什么?

在加入握手期间验证用户令牌,并授权用户访问特定主题,从而保护 Phoenix Channels。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Elixir & Phoenix: Scalable Backend Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Elixir & Phoenix: Scalable Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「频道认证与授权」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Elixir & Phoenix: Scalable Backend Development 课中编写并运行代码吗?

能。每节 Elixir & Phoenix: Scalable Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Phoenix Channels 简介
  2. 广播与发布/订阅消息
  3. 在线状态与实时数据更新
  4. 频道认证与授权
← 返回 Elixir & Phoenix: Scalable Backend Development