yii+swoole上手websocket(2)—— 鉴权

给自己找一点事情做~

why

安全最重要
保护数据~

how

参考jwt

userId = $userId;
        $this->currentTime = time();
    }

    public function createToken()
    {
        $split = self::SPLIT;
        return sprintf(
            '%s%s%s%s%s',
            $this->userId,
            $split,
            $this->currentTime,
            $split,
            $this->getSign($this->userId, $this->currentTime)
        );
    }

    public function validateToken($token)
    {
        list($userId, $time, $token) = explode(self::SPLIT, $token);
        if ($token != $this->getSign($userId, $time)) {
            throw new \Exception('token无效');
        }
        if ($this->currentTime - $time > self::TOKEN_TIMEOUT) {
            throw new \Exception('token已失效');
        }
        return $userId;
    }

    private function getSign($userId, $time)
    {
        $split = self::SPLIT;
        return md5(sprintf('%s%s%s%s%s', $userId, $split, $time, $split, self::SALT));
    }
}

调用

通过同步或者异步的方式,在客户端获取token【web的方式已经经过一层鉴权了】
再将token传给web socket后台,在后台记录该连接已经鉴权通过【可以将fd跟用户id做一层绑定记录到缓存中】

private function bind($token)
{
    $userId = (new SocketAuth())->validateToken($token);
    echo "userId: {$userId}". PHP_EOL;
    return ['code' => 200, 'msg' => 'success', 'data' => ['userId' => $userId]];
}

缺陷

跟jwt缺点相同,无法主动失效token,也无法禁止重复鉴权

你可能感兴趣的:(yii+swoole上手websocket(2)—— 鉴权)