0Pricing
Elixir & Phoenix: Scalable Backend Development · Lezione

Autenticazione e autorizzazione dei canali

Protegga i Phoenix Channels verificando i token degli utenti durante l'handshake di join e autorizzando l'accesso a topic specifici.

Autenticazione e autorizzazione dei canali è una lezione Elixir & Phoenix: Scalable Backend Development gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Elixir & Phoenix: Scalable Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Autenticazione e autorizzazione dei canali» è gratuita?

Sì — il testo completo di «Autenticazione e autorizzazione dei canali» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Elixir & Phoenix: Scalable Backend Development, passa a CoddyKit PRO. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.

Cosa imparerò in «Autenticazione e autorizzazione dei canali»?

Protegga i Phoenix Channels verificando i token degli utenti durante l'handshake di join e autorizzando l'accesso a topic specifici. Eserciti Elixir & Phoenix: Scalable Backend Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Elixir & Phoenix: Scalable Backend Development?

Non è richiesta alcuna esperienza precedente. Elixir & Phoenix: Scalable Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Autenticazione e autorizzazione dei canali»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Elixir & Phoenix: Scalable Backend Development?

Sì. Ogni lezione Elixir & Phoenix: Scalable Backend Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Introduzione ai Phoenix Channels
  2. Broadcasting e messaggistica Pub/Sub
  3. Presence e aggiornamenti dei dati in tempo reale
  4. Autenticazione e autorizzazione dei canali
← Torna a Elixir & Phoenix: Scalable Backend Development