thscz / query-signer
为指定的查询值创建控制哈希并验证它们
2.0.0
2019-09-05 07:09 UTC
Requires
- php: >= 7.0
Requires (Dev)
- phpunit/phpunit: ^5
This package is auto-updated.
Last update: 2024-09-05 19:19:52 UTC
README
这个工具是在我学习和尝试PHP OOP、Composer和PHPUnit的过程中创建的。
用法
composer require thscz/query-signer
签名
例如:file orders.php - 用户想要签名 "id" 值(45623)。
require_once 'vendor/autoload.php'; // ... // <a href="/order/45623">Order detail</a> $querySigner = new \THSCZ\QuerySigner\QuerySigner('supersecrtet'); $hash = $querySigner->sign([45623]); echo '<a href="/order/45623/&hash='. $hash .'">Order detail</a>';
验证
在验证页面上
// /order/45623/&hash=xxx require_once 'vendor/autoload.php'; $hash = filter_input(INPUT_GET, 'hash'); $orderId = filter_input(INPUT_GET, 'orderId'); $querySigner = new \THSCZ\QuerySigner\QuerySigner('supersecrtet'); if ($querySigner->validate([$orderId]) { // approved } else { // denied }
使用过期存储
您可以使用秒作为TTL(生存时间)创建哈希。为此选项,您必须使用实现了ExpirationStoreInterface并存储有关哪些哈希具有哪些过期信息的过期存储。
interface ExpirationStoreInterface { /** * @param $hash string created by QuerySigner * @param $timestamp integer UNIX timestamp value when hash expires * @throws ExpirationStoreException */ public function set(string $hash, int $timestamp): void; /** * @return integer|null UNIX timestamp value when hash expires * @throws ExpirationStoreException */ public function get(string $hash): ?int; /** * Deletes expiration information for hash * @param $hash string created by QuerySigner * @throws ExpirationStoreException */ public function revoke(string $hash): void; }
此包附带一个非常简单的FileExpirationStore,该存储将信息过期值存储在文件系统中。过期存储是QuerySigner类的第二个参数。
require_once 'vendor/autoload.php'; // ... // <a href="/order/45623">Order detail</a> $querySigner = new \THSCZ\QuerySigner\QuerySigner('supersecrtet', new \THSCZ\QuerySigner\Store\FileExpirationStore(__DIR__ . '/var/signs')); // hash is now valid for current UNIX timestamp + 60 seconds $hash = $querySigner->sign([45623], 60); echo '<a href="/order/45623/&hash='. $hash .'">Order detail</a>';
Idea for this little tool came to my mind when I was working on some
3rd party exotic system, that was unable to validate that item belonged
really to signed user