Authenticate websocket connection in Dart using shelf_auth and shelf_web_socket

不问归期 提交于 2019-12-11 08:27:19

问题


Using shelf_auth I can extract current user information from request this way:

getAuthenticatedContext(request)
  .map((ac) => ac.principal.name)
  .getOrElse(() => 'guest')

but, obviously, I need a request for that to work :) On the other hand, using shelf_web_socket, establishing of websocket connection executes handler like that:

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 forward original socket connection request to my handleWS, to be able to know which user just connected to server.


Another question is what is best practice to store these open sockets, to being able to send broadcast messages to all connected clients, and delete corresponding socket when it's closed. First what is coming to my mind is to store sockets in a map like Map<int,CompatibleWebSocket>, where int is CompatibleWebSocket.hash().

Then I can iterate over Map.values() to do broadcast, and delete by key when connection is closed.

I can't get if that technique overcomplicated for such task and maybe exist more convenient way doing that, like storing them in a list? Or can I join Streams somehow for broadcasting?

来源:https://stackoverflow.com/questions/30411169/authenticate-websocket-connection-in-dart-using-shelf-auth-and-shelf-web-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!