You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This protocol doesn’t prescribe any particular way that servers can authenticate clients during the WebSocket handshake. The WebSocket server can use any client authentication mechanism available to a generic HTTP server, such as cookies, HTTP authentication, or TLS authentication.
importurlfrom"url";importWebSocketfrom"ws";importdebugfrom"debug";importmomentfrom"moment";import{Ticket}from"../models";constdebugInfo=debug("server:global");// server 可以是http server 实例constwss=newWebSocket.Server({ server });wss.on("connection",async(ws)=>{constlocation=url.parse(ws.upgradeReq.url,true);constcookie=ws.upgradeReq.cookie;debugInfo("ws request from:"+location,"cookies:",cookie);// issue & send ticket to the peerif(!checkIdentify(ws)){terminate(ws);}else{constticket=issueTicket(ws);awaitticket.save();ws.send(ticket.pojo());ws.on("message",(message)=>{if(!checkTicket(ws,message)){terminate(ws);}debugInfo("received:%s",message);});}});functionissueTicket(ws){constuniqueId=ws.upgradeReq.connection.remoteAddress;returnnewTicket(uniqueId);}asyncfunctioncheckTicket(ws,message){constuniqueId=ws.upgrade.connection.remoteAddress;constrecord=awaitTicket.get(uniqueId);consttoken=message.token;return(record&&record.expires&&record.token&&record.token===token&&moment(record.expires)>=moment());}// 身份检查,可填入具体检查逻辑functioncheckIdentity(ws){returntrue;}functionterminate(ws){ws.send("BYE!");ws.close();}
扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。
一、WebSocket 协议
WebSocket 是个好东西,为我们提供了便捷且实时的通讯能力。然而,对于 WebSocket 客户端的鉴权,协议的 RFC 是这么说的:
也就是说,鉴权需要自己动手
二、协议原理
WebSocket 是独立的、创建在 TCP 上的协议。
为了创建 Websocket 连接,需要通过浏览器发出请求,之后服务器进行回应,这个过程通常称为“握手”。
实现步骤
直观的协商及通讯过程:
三、鉴权授权实现方案
通过对协议实现的解读可知:在 HTTP 切换到 Socket 之前,没有什么好的机会进行鉴权,因为在这个时间节点,报文(或者说请求的 Headers)必须遵守协议规范。但这不妨碍我们在协议切换完成后,进行鉴权授权:
3.1 鉴权
3.2 授权
服务端在连接建立时,颁发一个 ticket 给 peer 端,这个 ticket 可以包含但不限于:
3.3 安全性补充说明
比如,这一套机制如何防范重放攻击?个人认为可以从以下几点出发:
3.4 代码实现
WebSocket 连接处理,基于 Node.js 的 ws 实现
授权用到的 Ticket(这里存储用到的是 knex + postgreSQL)
utils 的哈希方法:
The text was updated successfully, but these errors were encountered: