# ws中的鉴权

鉴权机制设计:

使用jsonwebtoken(jwt)方式进行鉴权:

服务端:

// 在message事件内部
    // 鉴权机制 -> 检验token的有效性
    if (msgObj.event === 'auth') {
      console.log('msg auth is: ' + msgObj.message)
      // 拿到token,并且去校验时效性
      jwt.verify(msgObj.message, 'secret', function (err, decode) {
        if (err) {
          // websocket返回前台一个消息
          console.log('auth error')
          return
        } else {
          // 鉴权通过的逻辑
          // 这里可以拿到decode,即payload里面的内容
          ws.isAuth = true
          return
        }
        console.log(JSON.stringify(decode));
      })
    }
    // 拦截,非鉴权的请求
    if (!ws.isAuth) {
      // 去给客户端发送重新鉴权的消息
      ws.send(JSON.stringify({
        event: 'noauth',
        message: 'please auth again, your token is expired!'
      }))
      return
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

客户端:

onOpen: function() {
  // 连接创建之时
  // 设置定时器 -> 如果超时或者服务端没有响应 ping/pong -> 断开与服务端的连接
  console.log("client is connected");
  this.checkServer();
  // 发送鉴权token,token -> expire
  const data = {
  event: "auth",
  message: "token", // localstorage, cookie/session -> koa/express
  };
  // 主动鉴权
  this.wsHandle.send(JSON.stringify(data));
},
1
2
3
4
5
6
7
8
9
10
11
12
13
上次更新: 2020/10/28 下午11:02:30