我的项目中使用的websocket 即时通讯一直没有加权限验证功能,就是简单的连接后发消息,但是最近面试的时候有人问我websocket如何鉴权,现在把这个漏洞补上
这是后端代码 go语言
路由代码
go
defaultRoutes.GET("/ws", func(ctx *gin.Context) {
t := ctx.Query("token")
token, _, err := middlewares.ParseToken(t)
if err != nil || !token.Valid {
ctx.JSON(400, gin.H{
"message": "token无效",
})
} else {
controllers.UserController{}.WS(ctx.Writer, ctx.Request)
}
})
websocket连接
go
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var conns []*websocket.Conn
go
func (this UserController) WS(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
println("upgrade错误:", err)
return
}
defer c.Close()
conns = append(conns, c)
for {
_, _, err := c.ReadMessage()
if err != nil {
println("read:", err)
break
}
}
}
下面是前端代码
ini
let token=sessionStorage.getItem("token")
const env = process.env.NODE_ENV
//token加载url里个人感觉最合适的方案
const url = env == 'development' ? "ws://localhost:8088/ws?token=" + token : "ws://114.116.249.103:8088/ws?token=" + token
const websocket = new WebSocket(url)
let socketState = ref(true)
websocket.onopen = (evt) => {
console.log("链接成功")
socketState.value = true
}
websocket.onmessage = (evt) => {
//这里是判断消息类型,自定义功能
if (evt.data == "xxx1") {
refreshChartJL()
} else if (evt.data == "xxx2") {
refreshChartMusic()
}
}
websocket.onclose = () => {
console.log("链接关闭")
socketState.value = false
}