ob-ivan/sd-csrf

此包的最新版本(v1.2)没有可用的许可证信息。

v1.2 2018-01-12 11:51 UTC

This package is auto-updated.

Last update: 2024-09-29 04:45:39 UTC


README

这是一个简单的唯一令牌实用工具,用于防止跨站请求伪造(CSRF)攻击。

安装

composer require ob-ivan/sd-csrf

使用方法

一般使用案例可以概述如下

  • 控制器请求一个令牌,csrf 管理器生成并存储在会话数据下的某个可重构键中。
  • 视图将令牌值打印到隐藏的输入框中。
  • 用户提交表单,令牌值随之传递到表单处理控制器。
  • 第二个控制器重构键,并要求管理器验证令牌值,如果值不同则拒绝表单。

这降低了表单在没有用户同意的情况下被发送的可能性。

请注意,管理器实例可以由依赖注入容器提供,也可以在调用时实例化,因为它是无状态的(虽然这不一定在未来保持不变)。

以下是一个示例代码

use SD\Csrf\Manager;

class CommentController {
    public function getFormAction($postId) {
        return $this->render('form.twig', [
            'postId' => $postId,
            'token' => $this->getCsrfManager()->get($this->getTokenKey($postId)),
        ]);
    }

    public function postFormAction($request) {
        $postId = $request->post->get('postId');
        $tokenValue = $request->post->get('token');
        if (!$this->getCsrfManager()->verify($this->getTokenKey($postId), $tokenValue)) {
            return $this->errorResponse('Csrf token verification failed');
        }
        // ...save comment...
    }

    private function getTokenKey($postId) {
        return "post_comment_token_$postId";
    }
}

相应的视图代码

<form action="POST">
    <input type="hidden" name="postId" value="{{ postId }}"/>
    <input type="hidden" name="token" value="{{ token.value }}"/>
    <textarea name="comment"></textarea>
    <button type="submit>Send it already</button>
</form>