a4sex/self-signed-token 问题修复 & 功能扩展

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

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

a4sex/self-signed-token

Composer 安装命令:

composer require a4sex/self-signed-token

包简介

A simple self-signed token based on a secret string and creation time.

README 文档

README

Simple, stateless, and secure tokens signed solely with a secret — no database, no network calls.

Packagist PHP License

Table of contents

  1. About
  2. Installation
  3. Quick start
  4. Token structure
  5. Time modes and TTL
  6. Public API
  7. Token validation
  8. Manual signature verification
  9. Helpers and utilities
  10. Key management (KeyStore)
  11. Requirements
  12. License

About

Self‑Signed Token produces self-signed tokens composed of the following parts:

  • an identifier (ID) with optional ID-section data;
  • a timestamp and arbitrary payload in the second section;
  • a cryptographic signature with an explicit algorithm (except for md5);
  • a meta section (time interpretation type and optional keyId).

Validation is fully local using the secret. No DB state is stored or queried. The library also includes a key management (KeyStore) module for generating, rotating, and storing secrets in a file.

Installation

composer require a4sex/self-signed-token

Quick start

use A4Sex\SelfSignedToken;

$tokenService = new SelfSignedToken(
    ttl: 60,
    secret: 'my-secret',
    options: [
        'algo' => 'md5',                 // md5|sha256|sha512|sha3-256|sha3-512
        'type' => 'expired',             // expired|created
        'keyId' => null,                 // optional key identifier
        'bypass' => false,               // globally skip checks
    ]
);

// Create a token
$token = $tokenService->create(payload: ['role','admin']);

// Validate token (signature and expiration)
$isValid = $tokenService->valid($token);

Token structure

<id[:idData...]>.<time[:data...]>.<signSection>.<metaSection>
  • ID section: id[:idData...]
  • PAYLOAD section: time[:data1[:data2...]]
  • SIGN section: if the algorithm is md5, it contains only <hash>; otherwise <algo>:<hash>
  • META section: keyId[:type[:version...]] or just type (defaults to expired)

Examples

user42.1716309450:role:admin.sha256:1cb7e4d8....created
id1:x.1700000000:foo.sha256:deadbeef.kid-1:created:v1
id2.1700000000.abcd.expired

Time modes and TTL

  • expired: the second section stores the expiration moment. If expire is not provided on create, it is computed as now + TTL.
  • created: the second section stores the creation time. Expiration is created + TTL.

Switch modes via the type option.

Public API

use A4Sex\SelfSignedToken;
use A4Sex\Entity\Token as TokenEntity;

$t = new SelfSignedToken(ttl: 120, secret: 's3cr3t', options: [
    'algo' => 'sha256',
    'type' => 'created',
    'keyId' => 'kid-1',
]);

// Generate ID (md5 based on secret + randomness)
$id = $t->generateId('prefix-');

// Create token
$token = $t->create(id: $id, expire: null, payload: ['role','admin']);

// Validate: returns token ID or false
$idOrFalse = $t->valid($token, $ignoreSign = false, $ignoreExpires = false);

// Parse into entity
$entity = $t->parse($token);            // TokenEntity

// Individual checks
$t->signed($entity);                     // true|false
$t->expired($entity);                    // true|false

// Control time/TTL
$t->syncTime();                          // refresh "current" time (auto on create/valid)
$t->setSync(false);                      // disable auto-sync to use fixed time
$t->setCreated(time());                  // set fixed "current" time when sync is off
$t->setTtl(300);                         // change TTL

// Global bypass (disable checks)
$t->setBypass(true);

TokenManager (DTO-based API)

For more structured token creation with comprehensive options validation, use TokenManager:

use A4Sex\Services\TokenManager;
use A4Sex\DTO\TokenDto;

$manager = new TokenManager(
    defaultSecret: 'my-secret',
    defaultTtl: 3600
);

// Create with options DTO
$dto = TokenDto::create();
$dto->payload = ['user_id' => 123, 'role' => 'admin'];
$dto->algo = 'sha256';
$dto->type = 'expired';
$dto->keyId = 'key-1';
$dto->version = '1.0';

$token = $manager->create($dto);

// Convenience methods
$token = $manager->createSimple(['user_id' => 456]);
$token = $manager->createWithId('custom-id', ['data' => 'value']);
$token = $manager->createExpiringAt(time() + 1800, ['action' => 'login']);
$token = $manager->createWithAlgorithm('sha512', ['secure' => true]);
$token = $manager->createWithKey('master-key', '2.0', ['access' => 'full']);

Available options in TokenDto:

  • id — explicit token ID
  • expire — expiration timestamp (auto-generated if not specified)
  • payload — array of payload data
  • secret — signing secret
  • ttl — time to live in seconds
  • algo — signature algorithm (md5, sha256, sha512, sha3-256, sha3-512)
  • type — token type (expired, created)
  • keyId — key identifier
  • version — token version
  • created — creation timestamp (auto-generated for 'created' type if not specified)
  • idData — additional ID section data
  • bypass — bypass validation flags

Fields available after parse():

  • TokenEntity::id() — token ID
  • TokenEntity::time() — time value from the PAYLOAD section
  • TokenEntity::payload() — payload array of strings
  • TokenEntity::sign() — signature
  • TokenEntity::alg() — signature algorithm
  • TokenEntity::keyId()keyId from META section (if any)
  • TokenEntity::type() — type (expired|created)
  • TokenEntity::version() — version (if any)

Token validation

$ignoreSignature = false;
$ignoreExpire    = false;

$isValid = $tokenService->valid($token, $ignoreSignature, $ignoreExpire);

You can disable all checks globally with setBypass(true).

Manual signature verification

use A4Sex\Services\Signer;

$entity = $tokenService->parse($token);

// Canonical string to sign: id:payload[:keyId]:secret
$canonical = $tokenService->signature($entity, 'my-secret');

$ok = Signer::verify($canonical, $entity->sign(), $entity->alg());

Helpers and utilities

  • Signer: create and verify signatures.

    • Supported algorithms: md5, sha256, sha512, sha3-256, sha3-512.
    • Example:

      use A4Sex\Services\Signer;
          
      $hash = Signer::sign('data', 'sha512');
      $ok   = Signer::verify('data', $hash, 'sha512');
      
  • TokenSections / entity sections: low-level classes to work with token parts (TokenIdSection, TokenPayloadSection, TokenSignSection, TokenMetaSection).

  • TrainParser: build and parse A:B:C strings + JSON round-trip helpers.

  • IdGenerator: simple random identifier based on md5(salt + uniqid(...)).

  • UuidGenerator: generate uuid4, uuid6, ulid.

  • A9Generator: fixed-length alphanumeric IDs (A–Z, 0–9) without collisions within a provided list.

Additionally: see docs/styleguide.md for token style guidance and docs/keystore.md for key management details.

Key management (KeyStore)

A small file-backed KeyStore to manage signing secrets:

  • Key: key model (id, secret, created, payload[]).
  • KeySet: a set of keys keyed by id.
  • KeyStorage: load/save KeySet from/to a text file. Line format: ID:SECRET[:CREATED[:PAYLOAD...]]. Includes reset() method to clear storage.
  • KeyGenerator: generate id (via A9Generator, default length 5) and secret (via IdGenerator).
  • KeyManager: high-level operations — add, rotate, revoke with auto-persist via KeyStorage.

Example:

use A4Sex\Key\KeyStorage;
use A4Sex\Key\KeyGenerator;
use A4Sex\KeyManager;

$storage = new KeyStorage(__DIR__ . '/keys.txt');
$manager = new KeyManager($storage);

// Create and add a new key
$generator = new KeyGenerator();
$key = $generator->generate(payload: ['scope','auth']);
$manager->add($key);

// Rotate secret for the existing id
$rotated = $manager->rotate($key->id());

Requirements

  • PHP ≥ 8.2
  • ext-hash extension
  • symfony/uid package (for UuidGenerator)

License

MIT licensed. See LICENSE.

a4sex/self-signed-token 适用场景与选型建议

a4sex/self-signed-token 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 480 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 04 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 a4sex/self-signed-token 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-04-05