Authenticating web server connection in Dart using shelf_auth and shelf_web_socket
Using shelf_auth I can extract current user info from a request like this:
getAuthenticatedContext(request)
.map((ac) => ac.principal.name)
.getOrElse(() => 'guest')
but obviously I need a request for it to work :) On the other hand, using shel_web_socket, establishing a websocket connection is done by a handler like this:
handleWS(CompatibleWebSocket ws){
// Here I should get user from getAuthenticatedContext()
// but I cannot due to absence of Request here.
ws.messages.listen(...);
};
rootRouter.get('/ws', webSocketHandler(handleWS), middleWare: authMiddleware);
But I have no idea how to redirect the original socket connection request to my handleWS to find out which user is just connected to the server.
Another question is, is it best to keep these open sockets so that you can broadcast messages to all connected clients and delete the corresponding socket when it is closed. It first occurs to me to store sockets on a type map Map<int,CompatibleWebSocket>
where int is CompatibleWebSocket.hash()
.
Then I can iterate over the Map.values()
broadcast and remove the key when the connection is closed.
I can't get it if this technique is too complicated for such a task and maybe there is a more convenient way to do this, like storing them in a list? Or can I somehow join Streams to stream?
source to share
No one has answered this question yet
See similar questions:
or similar: