Search⌘ K
AI Features

Add Authorization to Channels

Understand how to implement channel authorization in Phoenix using socket state-based security. Learn to restrict user access to channels by validating user IDs stored in socket assigns, ensuring users only join their authorized topics. This lesson guides you through practical examples and testing steps for secure real-time communication.

Socket authentication is not always enough to fully secure our applications. For example, we could have a Socket that stores the authenticated user ID in the Socket state and allows a connection. When a client attempts to join "user:1" Channel, but they are user ID 2, we should reject the Channel join request. The client should only have access to topics that are relevant to them. We can do that with Channel authorization.

Types of channel authorizations

When a client joins a Channel, the Channel’s join/3 function is invoked. We can add authorization to our Channel by making this function check for a valid token. There are two options for how to add Channel authorization:

  • Parameter-based: Parameters can optionally be sent when a Channel topic is joined. The client’s authentication token is sent via these parameters, and the Channel can authorize the topic using the data encoded into the token.

  • Socket state-based: We can store information about the current connection, such as the connected user’s ID or token, when a ...