Why Restrict Access?

Explore the concept of access restrictions in this lesson.

Overview

The last section explored the basics of real-time applications powered by Channels, which let us build simple real-time applications. However, there’s still more we need to know to build full-featured applications. This section will cover adding access restrictions to Sockets and Channels.

We’ll start this section by examining how to restrict access to Channels and Sockets to ensure that data is provided only to the right users. We’ll use a Phoenix.Token to pass authentication information from the server to the view and then will use that to add Channel access restriction to the JavaScript client. We’ll learn when to use a single Socket or multiple Sockets in our applications, based on the restriction needs of our system.

Let’s jump into what access restriction is and why it’s crucial to add to our applications.

Reasons for restricting access

It has been common to hear about data leaks from improperly secured data or endpoints. This type of security issue can hit any application, including ones based on Phoenix Channels. Luckily, there is a built-in mechanism to close these security vulnerabilities.

There are two different types of access restrictions that we’ll focus on. The first type of restriction is authentication, which prevents non-users from accessing our application. If someone with malicious intent discovers our Socket connection URL and then successfully connects, they may be able to access more of our system.

The second type of restriction is authorization, which prevents users from accessing each other’s data. If our application exposed information about a particular user, even non-sensitive information, we would want only that specific user to see it.

We can use authentication and authorization to solve the problem of access restriction. To prevent non-users from connecting to our application, we add authentication to the Socket. When we want to restrict access to user data, we add authorization to the Channel and topic. We’ll use Socket authentication later in the course when we add an administrator portal, and we’ll use Channel authorization when allowing a shopper to join a cart:{userId} Channel. The combination of restricting access to Sockets and Channels gives us the most restrictive and secure application.

Phoenix provides two different entry points where we can add access restrictions. Socket authentication is handled in the Socket.connect/3 function, and Channel authorization is dealt with in the Channel.join/3 function. Let’s look at each and consider when we might want to use one over the other. We’ll use both types of restrictions to secure our real-time application fully.

Get hands-on with 1000+ tech skills courses.