Channelの認証と認可
joinハンドシェイク中にユーザートークンを検証し、特定のトピックへのアクセスを認可することで、Phoenix Channelsを保護します。
「Channelの認証と認可」はCoddyKit上の無料Elixir & Phoenix: Scalable Backend Developmentレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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
endGenerating 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: :errorAssigning 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
endScoping 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
endClient-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_ageshort for sensitive apps - Refresh tokens before they expire
- Handle the socket
onErrorevent 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/3usingPhoenix.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.
よくある質問
「Channelの認証と認可」レッスンは無料ですか?
はい。「Channelの認証と認可」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Elixir & Phoenix: Scalable Backend Developmentコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Elixir & Phoenix: Scalable Backend Developmentコースには全4レッスンが含まれています。
「Channelの認証と認可」で何を学びますか?
joinハンドシェイク中にユーザートークンを検証し、特定のトピックへのアクセスを認可することで、Phoenix Channelsを保護します。 ブラウザで直接実行するハンズオンコードでElixir & Phoenix: Scalable Backend Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Elixir & Phoenix: Scalable Backend Developmentを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのElixir & Phoenix: Scalable Backend Developmentは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「Channelの認証と認可」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このElixir & Phoenix: Scalable Backend Developmentレッスンでコードを書いて実行できますか?
はい。すべてのElixir & Phoenix: Scalable Backend Developmentレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。