rhubarbphp / module-csrfprotection
提供基于令牌的CSRF保护的方法
1.1.3
2024-06-06 11:03 UTC
Requires
- rhubarbphp/rhubarb: ^1.7.9
Requires (Dev)
- codeception/codeception: ^2.0.0
- codeception/specify: ^0.4.6
- codeception/verify: ^0.4.0
This package is auto-updated.
Last update: 2024-09-06 11:28:06 UTC
README
提供CSRF保护机制
用法
只需使用composer要求模块
composer require rhubarbphp/module-csrfprotection
提供了两种类型的验证
头部验证
只需调用库中的 validateHeaders
方法,将Origin和Referrer头部与活动请求进行比较。
CsrfProtection::singleton()->validateHeaders($request);
$request 应该是活动的 WebRequest 对象。如果您没有它的引用,您可以使用
$request = Request::current();
此验证应针对每个POST请求进行。它也可以用于GET请求,但并不推荐,因为它会在客户端第一次向网站发出请求时失败。
Cookie验证
此方法应与头部验证结合使用,并将提交的值与存储在客户端cookie中的先前生成的随机令牌进行比较。
在输出表单标签时,包括CSRFcookie令牌
$csrfProtector = CsrfProtection::singleton();
print '<input type="hidden" name="' . CsrfProtection::TOKEN_COOKIE_NAME . '" value="' . htmlentities($csrfProtector->getCookie()) . '" />';
在处理回发时,验证头部和cookie
if ($request->server('REQUEST_METHOD') == 'POST'){ CsrfProtection::singleton()->validateHeaders($request); CsrfProtection::singleton()->validateCookie($request); }
处理失败
如果验证失败,将抛出 CsrfViolationException,应捕获并适当地处理。