1
0
mirror of https://gitee.com/koogua/course-tencent-cloud.git synced 2025-06-23 03:50:56 +08:00

优化csrf_token

This commit is contained in:
xiaochong0302 2020-05-05 17:32:50 +08:00
parent 3c1c1d69b4
commit 740b4d952a

View File

@ -2,7 +2,7 @@
namespace App\Library; namespace App\Library;
use App\Library\Cache\Backend\Redis as RedisCache; use Phalcon\Cache\Backend\Redis as RedisCache;
use Phalcon\Di; use Phalcon\Di;
use Phalcon\Session\Adapter\Redis as RedisSession; use Phalcon\Session\Adapter\Redis as RedisSession;
use Phalcon\Text; use Phalcon\Text;
@ -37,6 +37,38 @@ class Security
$this->generateToken(); $this->generateToken();
} }
public function generateToken()
{
$this->tokenKey = $this->session->getId();
$key = $this->getCacheKey($this->tokenKey);
$lifetime = $this->options['lifetime'];
$content = [
'hash' => Text::random(Text::RANDOM_ALNUM, 32),
'expire' => time() + $lifetime,
];
$cacheContent = $this->cache->get($key);
if ($cacheContent) {
$this->tokenValue = $cacheContent['hash'];
if ($cacheContent['expire'] < time() + $lifetime / 2) {
$this->cache->save($key, $content, $lifetime);
$this->tokenValue = $content['hash'];
}
} else {
$this->cache->save($key, $content, $lifetime);
$this->tokenValue = $content['hash'];
}
}
protected function getCacheKey($tokenKey)
{
return "csrf_token:{$tokenKey}";
}
public function getTokenKey() public function getTokenKey()
{ {
return $this->tokenKey; return $this->tokenKey;
@ -47,49 +79,15 @@ class Security
return $this->tokenValue; return $this->tokenValue;
} }
public function generateToken()
{
$this->tokenKey = $this->session->getId();
$key = $this->getCacheKey($this->tokenKey);
$content = [
'hash' => Text::random(Text::RANDOM_ALNUM, 32),
'time' => time(),
];
$lifetime = $this->options['lifetime'];
$cache = $this->cache->get($key);
if ($cache) {
$this->tokenValue = $cache['hash'];
if (time() - $cache['time'] > $lifetime / 2) {
$this->cache->save($key, $content, $lifetime);
$this->tokenValue = $content['hash'];
}
} else {
$this->cache->save($key, $content, $lifetime);
$this->tokenValue = $content['hash'];
}
}
public function checkToken($tokenKey, $tokenValue) public function checkToken($tokenKey, $tokenValue)
{ {
$key = $this->getCacheKey($tokenKey); $key = $this->getCacheKey($tokenKey);
$content = $this->cache->get($key); $content = $this->cache->get($key);
if (!$content) { if (!$content) return false;
return false;
}
return $tokenValue == $content['hash']; return $tokenValue == $content['hash'];
} }
protected function getCacheKey($tokenKey)
{
return "csrf_token:{$tokenKey}";
}
} }