webiik /csrf
1.0
2019-02-28 21:18 UTC
Requires
- php: >=7.2
- webiik/session: ^1
- webiik/token: ^1
This package is auto-updated.
Last update: 2024-09-29 05:28:17 UTC
README
Csrf
该Csrf提供CSRF保护。
安装
composer require webiik/csrf
示例
$csrf = new \Webiik\Csrf\Csrf($token, $session); $token = $csrf->create(); // Now send the $token to the next request, e.g. using $_POST...
在下一个请求中验证token
$csrf = new \Webiik\Csrf\Csrf($token, $session); if ($csrf->validate($_POST[$csrf->getName()])) { // CSRF token is valid }
配置
setName
setName(string $name): void
setName() 设置自定义CSRF token名称,默认名称为'csrf-token'。它也是CSRF token的session键。
$csrf->setName('my-csrf-token');
setMax
setMax(int $max): void
setMax() 设置可以在session中存储的最大CSRF token数量。默认数量是5。这意味着,例如,用户可以同时打开最多5个受CSRF保护的表单。如果超过此限制,方法create()
不会生成新的CSRF token,而是返回最后一个生成的token。
$csrf->setMax(5);
节省资源,不要设置过大的数字。
生成
create
create(bool $safe = false): string
create() 返回16位长的CSRF token并将其存储在session中。如果您想生成安全的token,将$safe参数设置为true。
$csrfToken = $csrf->create();
安全的token生成较慢且需要更多资源。
验证
validate
validate(string $token, bool $safe): bool
$validate() 验证 $token 是否与session中存储的所有CSRF token匹配。如果 $token 有效,则返回true并从session中删除有效的token。如果您想使用时间攻击安全的验证,将 $safe 参数设置为 true。
$csrf->validate($token);
时间攻击安全的验证较慢且需要更多资源。