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
Yannick
Yannick•2y ago
Discord for example uses an identity message
Penca53
Penca53OP•2y ago
So there is no "straightforward" way to authenticate it using nextauth data?
dan
dan•2y ago
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.
Penca53
Penca53OP•2y ago
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?
Tom
Tom•2y ago
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)
Penca53
Penca53OP•2y ago
so the cookie would be sent in the initial startup request to the server? I could try that, yeah
Tom
Tom•2y ago
yeah just like a noraml http request
dan
dan•2y ago
I'm using socket.io here but thats the general idea. https://avrg.dev/wUGIX.png
Penca53
Penca53OP•2y ago
I didn't know that where is this snippet of code located?
dan
dan•2y ago
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
Penca53
Penca53OP•2y ago
a websocket server on serverless? Or did I miss something?
dan
dan•2y ago
no this isnt deployed on serverless that is being self hosted
Penca53
Penca53OP•2y ago
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?
dan
dan•2y ago
the code in that wont work on serverless due to the custom server. a hosted ws server doesnt work on serverless
Penca53
Penca53OP•2y ago
yeah yeah, just making sure I wasn't paying a EC2 instance for no reason 😄
dan
dan•2y ago
the next call is socket.io sincei added that code in a middlewear
Penca53
Penca53OP•2y ago
Ok, I've successfully implemented it using socket.io (never used it, but feels very comfortable). Thanks! @dan @Tom3
dan
dan•2y ago
np
Penca53
Penca53OP•2y ago
how do I properly mark it as solved and close the thread?
dan
dan•2y ago
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
Want results from more Discord servers?
Add your server