atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
950 stars 86 forks source link

Decompose session decrypt / support websockets #268

Open IlyaSemenov opened 4 days ago

IlyaSemenov commented 4 days ago

As a developer, I need to authenticate users inside a websocket session. In nuxt (h3), defineWebSocketHandler provides the API which doesn't pass the originating H3Event, only raw URL and headers.

I assumed there would be a low-level function such as getUserSessionFromHeaders({ ... }) or getUserSessionFromCookie("....") but I didn't manage to find one. getUserSession seems to be simply calling h3.useSession and the whole machinery seems to expect the full blown H3Event even though in fact it only needs a string.

I believe the documentation should include a recommended recipe for websocket users / other non-h3event authentication needs.

In the meanwhile, I ended up with a quite awkward approach where I have a GET API handler that encrypts the result of requireUserSession, then call it on the client side and push the encrypted session to websocket, which then decrypts it (and also handles expiration to prevent replay attacks). This is a lot of redundant code and an extra HTTP request per connection, and definitely could be improved if there were a way to directly decode the raw nuxt-session cookie content.

atinux commented 3 days ago

Hey @IlyaSemenov

I believe this issue should be opened on H3 side actually on how to handle session with the websocket handler.