WebSocket connection authentication
How would you authenticate a ws connection? I was thinking about sending the session token, but I'm not sure if that's secure. Moreover, I'm haven't found an easy way to get the session token, apart from querying the DB. Any ideas?
20 Replies
Discord for example uses an identity message
So there is no "straightforward" way to authenticate it using nextauth data?
Depending on what you are using for the websocket server but you would be able to get the cookie from the initial request (before the connection is upgraded to ws(s). You can then use that cookie to check against the session table from nextauth.
right now it is a basic nodejs server. What do you mean with
you would be able to get the cookie from the initial request
?websockets start out as http requests and get upgraded. he means that you can probably still auth the user using the cookie that gets uploaded with that original request
(not that ive done it, but i think he's right)
so the cookie would be sent in the initial startup request to the server? I could try that, yeah
yeah just like a noraml http request
I'm using socket.io here but thats the general idea. https://avrg.dev/wUGIX.png
I didn't know that
where is this snippet of code located?
GitHub
Kurumi/websocket.ts at refactor/t3 · iAverages/Kurumi
Simple note taking app with Monaco (VSCode Editor) - Kurumi/websocket.ts at refactor/t3 · iAverages/Kurumi
a websocket server on serverless? Or did I miss something?
no this isnt deployed on serverless
that is being self hosted
but if this was on Vercel, this would be serverless, right?
so I basically have to take inspiration from this, ignoring next related stuff, like the
next()
calls, correct?the code in that wont work on serverless due to the custom server. a hosted ws server doesnt work on serverless
yeah yeah, just making sure I wasn't paying a EC2 instance for no reason 😄
the next call is socket.io sincei added that code in a middlewear
Ok, I've successfully implemented it using socket.io (never used it, but feels very comfortable). Thanks! @dan @Tom3
np
how do I properly mark it as solved and close the thread?
Right click the solution answer. https://avrg.dev/9DFJn.png I dont think you can close threads but it'll get auto archived after how ever logn