jerrygolero

jerrygolero

Implementing Token-Based Authentication with Phoenix LiveView: Best Practices and Handling Reconnects

Hi everyone!

I’m working on an authentication system for my app using Phoenix LiveView and considering implementing token-based authentication (e.g., with Phoenix.Token or JWT). I’d love to hear how others approach this, especially when it comes to safely handling reconnections after the WebSocket connection drops.

Here’s the workflow I’ve been ideating:

  1. A user submits their email and password for authentication.
  2. If the system successfully authenticates the user, it generates a token (using Phoenix.Token, JWT, or something similar).
  3. The system attaches the token to the LiveView socket (or session—still deciding).
  4. If the user’s WebSocket connection drops (e.g., due to network issues), the browser attempts to reconnect.

Here’s where I’m stuck:

  • How can I ensure the connection safely reuses the already-generated token during the LiveView reconnection process?
  • Should I rely on the LiveView session or some other mechanism to persist and validate the token securely for subsequent reconnect attempts?
  • Are there any gotchas I should watch out for when integrating token-based authentication into a LiveView app?

Any advice, insights, or examples from your own implementations would be greatly appreciated!

Thanks in advance!

Most Liked

hubertlepicki

hubertlepicki

You should probably use mix phx.gen.auth even on a side project just to follow the code if you want to implement it from scratch. They’re using Phoenix.Token and save it in the session.

There should be nothing you have to do for session re-connects.

Also: you can use Phoenix.Token or JWT but you do not have to.

What phx.gen.auth is doing is actually different - they do not use either. They just generate a simple random token value using :crypto.strong_rand_bytes and then insert that token along with user_id to a database table.

After that’s done, the value of the token is set in the session.

Session is signed, so in theory they could have put user_id there, but their approach is smarter as they store the token in the session, but the mapping to user_id on server, which allows them to invalidate the session wherever they want by just deleting the token on the server.

This is the approach I have adopted across my apps, not just LiveView, and this has saved me a lot of trouble.

Phoenix.Token or JWT could be used instead of Phoenix sessions. You usually use them with APIs. They’re not suitable for session/cookie based authentication because of their size, which can be big and your session storage is probably in cookie, meaning that it has a hard limit that is not too big at all.

So that’s my gotcha at the end. I do advise you use mix phx.gen.auth and spend an hour or so with generated code, it will be very educational!

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement