corviz/csrf-token

创建/验证 CSRF 令牌

v1.0 2022-05-10 01:10 UTC

This package is auto-updated.

Last update: 2024-09-10 06:14:19 UTC


README

创建/验证 CSRF 令牌

使用 Composer 安装

composer require corviz/csrf-token

基本用法

创建令牌字符串

<?php

use Corviz\CsrfToken\Token;

$token = new Token();
$tokenStr = $token->generate();
echo $tokenStr;

?>
<form method="post">
    <input type="hidden" name="csrf_token" value="<?php echo $tokenStr; ?>"/>
    <!-- ... -->
</form>

验证令牌字符串

<?php

use Corviz\CsrfToken\Token;

$token = new Token();
$tokenStr = $_POST['csrf_token'];

if ($token->verify($tokenStr)) {
    //Valid token
} else {
    //Invalid token
}

重要!
默认情况下,密钥和令牌存储在会话中。如果您使用默认组件,请确保调用 session_start(),否则将抛出异常。

高级

根据当前表单的不同令牌

在不同的页面/表单中使用不同的令牌是一个好主意。要做到这一点,您只需要在生成/验证令牌字符串之前设置一个标识符。

<?php

use Corviz\CsrfToken\Token;

$token = new Token();
$identifier = 'form-1';

//Create new token string
$tokenStr = $token->generate($identifier);

//Verify incoming token string:
echo $token->verify($_POST['csrf_token'], $identifier) ? 'Valid csrf token' : 'Invalid csrf token';

自定义存储

如果您想使用会话之外的其他存储,首先您需要声明它。

<?php

use Corviz\CsrfToken\StorageInterface;

class DatabaseStorage implements StorageInterface
{
    public function get(string $key) : mixed
    {
        //read '$key' from db
    }

    public function set(string $key, mixed $value) : void
    {
        //write '$key' value to db
    }

    public function isset(string $key) : bool
    {
        //checks if $key exists in database
    }

    public function unset(string $key) : void
    {
        //delete $key from db
    }
}

然后,只需在您的令牌中设置它,在生成令牌字符串之前。

<?php

use Corviz\CsrfToken\Token;

$token = new Token();
$storage = new DatabaseStorage();
$token->setStorage($storage);

echo $token->generate();

在检查之前也要设置。

<?php

use Corviz\CsrfToken\Token;

$token = new Token();
$storage = new DatabaseStorage();
$token->setStorage($storage);

echo $token->verify($_POST['csrf_token']) ? 'Valid' : 'Invalid';

自定义密钥提供者

与自定义存储类似,要创建自定义密钥提供者,您必须声明它。

<?php

use Corviz\CsrfToken\KeyProviderInterface;
use \Corviz\CsrfToken\StorageInterface;

class MyKeyProvider implements KeyProviderInterface
{
    private StorageInterface $storage;
    
    public function generateKey() : string|false
    {
        $index = '...';
        
        if (!$this->storage->isset($index)) {
            // generate key and store it
            $hashKey = '...';
            $this->storage->set($index, $hashKey);
        }
        
        return $this->storage->get($index);
    }
    
    public function __construct(StorageInterface $storage) 
    {
        $this->storage = $storage;
    }
}

在生成或验证令牌字符串之前,设置您的密钥提供者。

<?php

use Corviz\CsrfToken\Token;

$token = new Token();
$keyProvider = new MyKeyProvider($storage);
$token->setKeyProvider($keyProvider);

echo $token->generate();

//or 

echo $token->verify($_POST['csrf_token']) ? 'Valid' : 'Invalid';