定制 pedroac/nonce 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

pedroac/nonce

Composer 安装命令:

composer require pedroac/nonce

包简介

A nonces manager usefull for preventing CSRF and replay attacks.

README 文档

README

Build Status Codacy Badge Support via PayPal

A nonce manager PHP library useful for preventing CSRF and replay attacks.

We may find several articles and videos explaining the vulnerabilities that nonces try to prevent:

It seems, though, that many PHP nonces libraries are too restrictive, coupled with some framework, hard to use or hard to understand how they work.

pedroac/nonce tries to solve those issues.

It allows choosing any PSR-16 implementation to store temporarily the nonces, nonces values generators, expiration intervals and even a DateTime provider to override the clock system (this feature is used for unit tests).

It also provides helpers to manage input, generate random nonces names and values, verify submitted tokens against the nonce and generate HTML elements.

Prerequisites

Installing

Run the command:

composer require pedroac/nonce

Usage

Examples

The HTML forms can be tested using a PHP built-in web server.
From the php/examples folder run the command:

php -S localhost:8000

Use the URL http://localhost:8000/ in a browser.

HTML form with a token

  1. Create a nonce form helper:
<?php
require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;
use \pedroac\nonce\Form\HtmlNonceField;
use \pedroac\nonce\Form\NonceForm;

// this handles automatically the input and nonce management
$form = new NonceForm(
    'token', // the HTML input name
    new NoncesManager(
      new FilesystemCache // a \Psr\SimpleCache\CacheInterface implementation
    )
);
// this will be used to generate a HTML input element
$htmlField = new HtmlNonceField($form);
  1. Check if a valid token was submitted:
if ($form->isSubmittedValid()) {
  /**
   * handle the success:
   * - if all form input is valid, show success page;
   * - otherwise, show an error page and the form again;
   */
}
  1. Check if an invalid token was submitted:
if ($form->isSubmittedInvalid()) {
  /**
   * handle failure:
   * - don't show the form again;
   * - show an error message;
   */
}
  1. Implement the HTML form:
<form method="POST">
    <?= $htmlField ?>
    <!-- more HTML -->
    <input type="submit" name="myform" value="Submit" />
</form>

The nonce is expired automatically when the token is verified with the NonceForm class.

General usage

  1. Instantiate a nonce manager:
<?php
require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;

$manager = new NoncesManager(new FilesystemCache);
  1. When a request is submitted, validate the submitted token and remove the nonce:
$isValidToken = false;
$isValidForm = false;
$wasSubmitted = filter_has_var(INPUT_POST, 'myform');
$tokenName = filter_input(INPUT_POST, 'token_name');
$tokenValue = filter_input(INPUT_POST, 'token_value') ?? '';

if ($tokenName) {
    $isValidToken = $manager->verifyAndExpire($tokenName, $tokenValue);
}
if ($wasSubmitted && $isValidToken) {
    // validate input
}
  1. Generate a nonce when appropriate:
if (!$wasSubmitted || (!$isValidForm && $isValidToken)) {
  $nonce = $manager->create();
}
  1. Use the nonce name and value to build, for instance, a HTML form:
<?php if ($nonce) : ?>
  <input type="hidden"
        name="token_name"
        value="<?= htmlspecialchars($nonce->getName()) ?>" />
  <input type="hidden"
        name="token_value"
        value="<?= htmlspecialchars($nonce->getValue()) ?>" />
  <input type="submit" name="myform" value="Submit" />
<?php endif; >

Options

Besides the nonces cache storage, it's possible to select the random nonce value generator and the expiration interval:

<?php
require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Cache\Simple\ArrayCache;
use \pedroac\nonce\NoncesManager;
use \pedroac\nonce\Random\HexRandomizer;

$manager = new NoncesManager(
    new ArrayCache(60),
    new HexRandomizer(32), // a \pedroac\nonce\Random implementation
    new \DateInterval('PT3H')
);

It's also possible to create a nonce with a specified name:

$user_id = $_SESSION['user_id'];
$tokenName = "{$user_id}_form";
$nonce = $manager->create($tokenName);

NonceForm default input source is $_POST, but it accepts any array input:

$form = new NonceForm(
    'token',
    new NoncesManager(
      new FilesystemCache
    ),
    filter_input_array(INPUT_GET) // use $_GET
);

Running the tests

Run from the library root folder:

php/vendor/bin/phpunit php/tests/ -c php/tests/configuration.xml

If the tests were successful, php/tests/coverage-html should have the code coverage report.

Generating the HTML documentation

Run from the library root folder:

sh scripts/generate-docs.sh

The generated documentation should be inside the folder docs.

Versioning

It should be used SemVer for versioning.

Authors

License

pedroac/nonce is released under the MIT public license.
See the enclosed LICENSE for details.

Acknowledgments

The library was developed as a private request response made by a Stackoverflow user.

pedroac/nonce 适用场景与选型建议

pedroac/nonce 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 235 次下载、GitHub Stars 达 4, 最近一次更新时间为 2018 年 03 月 31 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「security」 「token」 「csrf」 「nonce」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 pedroac/nonce 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 pedroac/nonce 我们能提供哪些服务?
定制开发 / 二次开发

基于 pedroac/nonce 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 235
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 14
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-03-31