# jwt **Repository Path**: fiberphp/jwt ## Basic Information - **Project Name**: jwt - **Description**: 🪪 FiberPHP JWT 认证组件 —— 基于 firebase/php-jwt 封装的 JWT 生成与验证,支持 HS256/RS256/ES256,开箱即用。 - **Primary Language**: PHP - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-08-23 - **Last Updated**: 2026-09-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # FiberPHP JWT JSON Web Token(RFC 7519)编解码器,零框架依赖的纯库实现(仅依赖 `ext-json` 与 `ext-openssl`)。支持 HS256/HS384/HS512 对称密钥与 RS256/RS384/RS512 非对称密钥,内置 exp/nbf/iss/aud 声明校验与时钟偏差容忍。 ## 环境要求 - PHP >= 8.3 - `ext-json` - `ext-openssl`(RS 系列算法签名需要) ## 安装 ```bash composer require fiberphp/jwt ``` ## 快速开始 ### HS256 对称密钥 ```php use FiberPHP\Jwt\Jwt; $jwt = new Jwt('your-secret-key', 'HS256'); // 签发 Token(默认 1 小时过期) $token = $jwt->encode([ 'sub' => 'user-1', 'name' => '张三', 'admin' => true, ], 3600); // 解码并验证(签名 + 过期 + nbf + iss + aud) $payload = $jwt->decode($token); ``` ### RS256 非对称密钥 ```php $jwt = new Jwt( secretOrPrivateKey: $privateKeyPem, // 签发时使用私钥 algorithm: 'RS256', publicKey: $publicKeyPem, // 验证时使用公钥 ); $token = $jwt->encode(['sub' => 'user-1'], 3600); $payload = $jwt->decode($token); ``` ## 配置说明 `Jwt` 构造参数: | 参数 | 默认值 | 说明 | |----------------------|---------|-------------------------------------------------| | `secretOrPrivateKey` | 必填 | HS 为 secret string,RS 为 PEM 私钥 | | `algorithm` | `HS256` | 签名算法:HS256/HS384/HS512/RS256/RS384/RS512 | | `publicKey` | null | PEM 公钥,仅 RS 验证时需要 | | `issuer` | null | 默认签发者(iss),encode 时注入、decode 时校验 | | `audience` | null | 默认受众(aud),encode 时注入、decode 时校验 | | `leeway` | 0 | 时钟偏差容忍(秒),用于 exp/nbf 校验 | `encode($payload, $ttl, $header)` 中 `ttl`:`>0` 写入 exp;`=0` 永不过期;`<0` 立即过期(负偏移)。 ## 特性 | 能力 | 说明 | |------------|---------------------------------------------------------| | 双算法族 | HMAC-SHA2 对称 / RSA-SHA2 非对称 | | 防算法混淆 | 解码时强制校验 header.alg 与实例算法一致,拒绝 `none` | | 标准声明 | 自动注入 iat/iss/aud,校验 exp/nbf/iss/aud | | 时钟容忍 | `leeway` 防止分布式时钟偏差导致误判 | | Base64URL | 标准 URL 安全编码,无填充 | | 不安全解码 | `decodeUnverified` 仅读 payload,用于调试(勿用于生产) | ## 错误处理 所有验证失败均抛出 `FiberPHP\Jwt\Exception\JwtException`(继承 `RuntimeException`),异常携带机器可读的 `reason` 标识: | reason | 场景 | |--------------|----------------------------------------------| | `format` | 三段格式错误、Base64URL/header/payload 解析失败 | | `algorithm` | 算法不受支持,或 token header.alg 与实例不一致 | | `signature` | 签名验证失败、RSA 验签未配置 publicKey | | `expired` | 已超过 exp(可用 `isExpired()` 判断) | | `not_before` | 当前时间早于 nbf | | `issuer` | iss 不匹配 | | `audience` | aud 不匹配 | | `encode` | 编码失败(如声明含非法 UTF-8) | ```php use FiberPHP\Jwt\Exception\JwtException; try { $payload = $jwt->decode($token); } catch (JwtException $e) { // 按 getReason() 分支处理,例如 expired 时触发刷新 Token http_response_code(401); } ``` `decodeUnverified()` 不校验签名与有效期,仅格式错误时抛异常,**禁止用于生产鉴权**。 ## License MIT License (c) 2026-present FiberPHP Contributors,详见 [LICENSE](LICENSE)。