websocket携带jwt token

在websocket中,目前未提供修改请求头字段的方法,不过可以借助于“Sec-WebSocket-Protocol”,将token放入请求头中,后端收到请求后,从请求头中取得token做校验。

即:在前端websocket中放入token

 let token=localStorage.getItem("token")
 this.socket = new WebSocket(terminalWsUrl,[token]);//在webscoket中放入token

后端接收到请求后,从header中取出“Sec-WebSocket-Protocol”,做校验

 token = context.Request.Header.Get("Sec-WebSocket-Protocol")
 if len(token) == 0 {
   ResponseError(context, 11000, errors.New("请求未携带token,无权限访问"))
   context.Abort()
   return
 }

另外需要注意的是,在响应头上添加Sec-Websocket-Protocol,如下是在grilla/websocket响应中设置Sec-Websocket-Protocol的方式

var upgrader = func(r *http.Request) *websocket.Upgrader {
	upgrader := &websocket.Upgrader{}
	upgrader.HandshakeTimeout = time.Second * 2
	upgrader.CheckOrigin = func(r *http.Request) bool {
		return true
	}
	upgrader.Subprotocols = []string{r.Header.Get("Sec-Websocket-Protocol")}  //设置Sec-Websocket-Protocol
	return upgrader
}

多数时候,浏览器出现下面异常提示信息,就是因为响应报文头中没有Sec-Websocket-Protocol导致的

WebSocket: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was receivedWebSocket:WebSocket

引用链接:
(1)https://blog.csdn.net/weixin_43277309/article/details/123129650
(2)https://www.jianshu.com/p/7b1deb1e0a07?utm_campaign=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com

posted @ 2022-12-14 13:26  cosmoswong  阅读(2608)  评论(0编辑  收藏  举报