Add Authorization to Channels

Learn how to add authorization to Channels.

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 Socket connection occurs. This state becomes available in Socket.assigns and can be used in our Channel’s join/3 function. We fully control the state at this point, so it is trusted.

There are advantages to the Socket state-based approach that make it the best choice most of the time. We can secure our application by passing a single token to the server on the Socket connection, rather than passing the token on every Channel join. This makes it much easier to write the code powering our authorization.

Socket state-based authorization

We’ll use Socket state-based authorization in the following examples. Let’s start by looking at securing a topic based on the topic’s name matching the provided user ID.

Get hands-on with 1000+ tech skills courses.