mirror of
https://gitee.com/koogua/course-tencent-cloud.git
synced 2025-06-22 19:44:02 +08:00
优化csrf_token
This commit is contained in:
parent
3c1c1d69b4
commit
740b4d952a
@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Library;
|
||||
|
||||
use App\Library\Cache\Backend\Redis as RedisCache;
|
||||
use Phalcon\Cache\Backend\Redis as RedisCache;
|
||||
use Phalcon\Di;
|
||||
use Phalcon\Session\Adapter\Redis as RedisSession;
|
||||
use Phalcon\Text;
|
||||
@ -37,6 +37,38 @@ class Security
|
||||
$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()
|
||||
{
|
||||
return $this->tokenKey;
|
||||
@ -47,49 +79,15 @@ class Security
|
||||
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)
|
||||
{
|
||||
$key = $this->getCacheKey($tokenKey);
|
||||
|
||||
$content = $this->cache->get($key);
|
||||
|
||||
if (!$content) {
|
||||
return false;
|
||||
}
|
||||
if (!$content) return false;
|
||||
|
||||
return $tokenValue == $content['hash'];
|
||||
}
|
||||
|
||||
protected function getCacheKey($tokenKey)
|
||||
{
|
||||
return "csrf_token:{$tokenKey}";
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user