0Pricing
Elixir & Phoenix: Scalable Backend Development · Lección

Autenticación y autorización de canales

Proteja sus Phoenix Channels verificando los tokens de usuario durante el handshake de unión y autorizando el acceso a temas específicos.

Autenticación y autorización de canales es una lección gratuita de Elixir & Phoenix: Scalable Backend Development en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Elixir & Phoenix: Scalable Backend Development, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Elixir & Phoenix: Scalable Backend Development incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Autenticación y autorización de canales» es gratis?

Sí — el texto completo de «Autenticación y autorización de canales» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Elixir & Phoenix: Scalable Backend Development, actualiza a CoddyKit PRO. El curso de Elixir & Phoenix: Scalable Backend Development incluye 4 lecciones en total.

¿Qué aprenderé en «Autenticación y autorización de canales»?

Proteja sus Phoenix Channels verificando los tokens de usuario durante el handshake de unión y autorizando el acceso a temas específicos. Practicas Elixir & Phoenix: Scalable Backend Development con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Elixir & Phoenix: Scalable Backend Development?

No se requiere experiencia previa. Elixir & Phoenix: Scalable Backend Development en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Autenticación y autorización de canales»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Elixir & Phoenix: Scalable Backend Development?

Sí. Cada lección de Elixir & Phoenix: Scalable Backend Development incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción a Phoenix Channels
  2. Difusión de mensajes y mensajería Pub/Sub
  3. Presence y actualizaciones de datos en tiempo real
  4. Autenticación y autorización de canales
← Volver a Elixir & Phoenix: Scalable Backend Development