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:
Logged-in user visits a page, WebSocket connection is established using a JWT token (user has completed login);
Users stays on page for ages, token expires eventually;
WebSocket connection no longer valid, so it starts rejecting client’s attempts (e.g. [info] Replied MyAppWeb.UserSocket :error );
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.
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"
})
I haven’t thought about checking the JWT token validity on the front-end, how would you do that? Or is there a library you’d recommend?
As per the second suggestion: we tried using socket.onError but as far as I remember, the error given is quite generic and didn’t give us enough information to handle this type of error specifically.
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.
@outlog@mikemccall I see, I like the idea of verifying it on the backend Perhaps I can use navigator.onLine to check if the user is offline and display an offline warning message on the screen; otherwise I can attempt an AJAX request to validate the token and deal with that accordingly. Do you think I’m missing anything, would that be sufficient?
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…
This was eating at me so I did a little research and I found this stack overflow answer.
Basically the websocket spec forbids reading the HTTP status code. Per the stack overflow answer I’d like throw in one more option I think is interesting.
From the post:
In your server-side logic, even when you ultimately want to reject the connection (like say the user is currently unauthenticated), do this instead:
Accept the WebSocket connection
Immediately close the connection with a custom close status
The client can now look at the CloseEvent.code to know why the connection was rejected.
I haven’t tried this in phoenix yet but I do plan to give a shot later today.