maer/csrf 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

maer/csrf

最新稳定版本:1.1.0

Composer 安装命令:

composer require maer/csrf

包简介

A small CSRF package for PHP

README 文档

README

Quickly generate and validate tokens to prevent Cross-Site Request Forgery (CSRF) attacks.

Important: This package only helps you with the CSRF tokens. To truly be safe from CSRF, you also need to protect yourself against Cross-site scripting (XSS) as well.

Install

Git clone or use composer to download the package with the following command:

composer require maer/csrf 1.*

Usage

Include composers autoloader or include the files in the src/ folder manually. (start with CsrfInterface.php-file)

Create a new instance

$csrf = new Maer\Security\Csrf\Csrf();

Important: You can create a new instance when ever in your application, but before you make any calls to it, you need to start the session yourself. This package does not make any assumptions on how you manage your sessions (you might use: session_start() or you might use Symfonys Session package etc...)

Approach 1: Manually add the hidden field

<form method="post" action="...">

    <input type="hidden" name="csrftoken" value="<?= $csrf->getToken() ?>" />

    ...

</form>

Approach 2: Generate the hidden field

<form method="post" action="...">

    <?= $csrf->getTokenField() ?>

    ...

</form>

Validate

When receiving the post:

if ($csrf->validateToken($_POST['csrftoken'])) {
    echo "Yay! It's a valid token!";
} else {
    echo "Nope. That token isn't valid!";
}

Extra goodies

Named tokens

All methods takes an optional $name argument. This gives you the option of having multiple tokens through out your application. For example:

$csrf->getToken();
$csrf->getToken('login-form');
$csrf->getToken('something-else');

The above will generate three different tokens and the same goes for the getTokenField()-method.

To validate named tokens, set the name as the second argument to the validateToken()-method:

$csrf->validateToken($_POST['csrftoken'], 'login-form');

Regenerate tokens

If you want to invalidate an existing token, use the regenerateToken()-method. This method also returns the new token, so if you want to have different tokens every time a form is loaded, you can use this method instead of generateToken()

$token = $csrf->regenerateToken();

// or for a named token
$token = $csrf->regenerateToken('login-form');

Reset/remove all tokens

This will remove all tokens, named or not.

$csrf->resetAll();

Note

If you have any questions, suggestions or issues, let me know!

Happy coding!

统计信息

  • 总下载量: 3.08k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 0
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-10-16