Different Types of Tokens
JSON Web Token
Phoenix.Token can help us in these situations. A widespread web standard for authentication is the
JSON Web Token JWT. JWTs are cryptographically secure but not encrypted, though an encrypted variant called JWE does exist. So, they meet the same security standard as
Phoenix.Token. However, one significant difference is that JWT is a standardized format that can be consumed easily in nearly any language, including the front-end client. We can use this in our client code to detect if a JWT expired before sending the credential to the server. We’ll have to do a bit more work to use JWTs than
Phoenix.Token because JWT support is not included out-of-the-box with Phoenix. JWTs are not a proper replacement for cookie-based authentication. They should only pass a user session between different parts of an application.
Author’s Note: Joken is my go-to library for handling JWTs in Elixir. I use it in all my Elixir projects and highly recommend it. We’ll use
Phoenix.Tokenin this course since it is already included and set up for our project. However, consider looking into JWT if you need a cross-language solution or if you need firmly secured tokens through standards such as RSA encryption.
Whether we’re using Phoenix Tokens, JWT, or another technology, it’s essential to set the token’s expiration to a low enough value. A token is the user’s way to get into our system, and a user has access for the duration of the token. Pick a token duration that is long enough to be convenient but short enough to provide security for our users—a good default is 10 minutes. Some techniques can invalidate tokens before they’re expired, such as token blocklists, but we won’t cover them in this course.
Socket authentication provides a nice layer of security, but it doesn’t cover everything. It is also essential to secure private topics at the Channel level.