给自己找一点事情做~
why
安全最重要
保护数据~
how
参考jwt
<?php
namespace app\services;
class SocketAuth
{
/** @const int 认证token超时时间 */
const TOKEN_TIMEOUT = 600;
const SALT = '1cc16f803dc544859c797a87ba58756c';
const PREFIX = 'SocketAuth';
const SPLIT = '.';
protected $userId;
private $currentTime;
public function __construct($userId = null)
{
$this->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,也无法禁止重复鉴权
网友评论