svilen

svilen

Author of Concurrent Data Processing in Elixir

Expired token for WS connection, how to handle on the front-end?

Hi everyone!

A colleague of mine asked this question on StackOverflow, but since he still hasn’t got a solution, I decided to post it here on his behalf:

In a nutshell:

  1. Logged-in user visits a page, WebSocket connection is established using a JWT token (user has completed login);
  2. Users stays on page for ages, token expires eventually;
  3. WebSocket connection no longer valid, so it starts rejecting client’s attempts (e.g. [info] Replied MyAppWeb.UserSocket :error );
  4. Front-end keeps re-connecting but unless the user refresh the page and logs in again, we have lost connection to WS

On the Phoenix side, I can see we can return only :error for connect/2 (I was hoping for a tuple with an addition message, but no luck) so I’m not sure if there is a way to let the client know what is the error? If the client knows that the error is, say “token expired”, then we can pop up a message using JS to tell the user that he/she needs to re-authenticate. Otherwise, if it is a network connection issue or something else, the current behaviour to keep reconnecting makes sense.

Any ideas are appreciated. Thanks!

Most Liked

outlog

outlog

I would not trust navigator.online I believe those things are not reliable under various circumstances (eg wifi up - but routing down, flaky cell connection etc etc.)
guess that is an additional advantage to the ajax request method.. since a timeout or any error (anything but 20x OK, or 401) means you are offline..

(btw remembered why I do the auth check in an ajax call - it’s because I can server side invalidate tokens (guardian_db))

So you could just verify token client side - but if you also want a reliable online/offline check I think the ajax call solves both issues in one go..

mikemccall

mikemccall

I don’t see a way to return a message in {:error, message} in phoenix, it expects {:ok, socket} or :error.

If you’re using a jwt you can check if it’s expired on the frontend. Where to do the check depends on your app. But you can always add the onError callback to the socket.

socket.onError((error) => { 
    // check jwt expiration and redirect to login
    // or
    // indicate to the user they are "offline"
   })

mikemccall

mikemccall

Yeah, it is pretty generic. There are a few jwt libraries out there that would help. Visit https://jwt.io/ and see which one fits your use case. Pretty much any of them from Auth0 are solid. I’ve had success with jsonwebtoken.

Or as @outlog mentioned you could make a request on error and let the server do that work.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement