From 6bd74bb7d28c31eca58b197832d41f431019ff37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E7=90=A6?= Date: Mon, 10 Aug 2026 13:58:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BE=9D=E8=B5=96=E3=80=81?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 2 ++ app/Service/common/JWTService.php | 20 ++++++++++++++++++-- config/nl.php | 6 ++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index 7d97071d..9d868cda 100644 --- a/.env.example +++ b/.env.example @@ -81,3 +81,5 @@ BASE_OLD_SHOP_API_URL=https://shop.xiaokang88.com # 密钥 ENCRYPT_KEY=3a8f9b2d7c1e4f8a9b2d7c1e4f8a9b2d7c1e4f8a9b2d7c1e4f8a9b2d7c1e4f8a +# JWT HS256 密钥(至少 32 字符;生产环境务必改成随机长串) +JWT_SECRET=nl_admin_jwt_secret_key_change_me_32b diff --git a/app/Service/common/JWTService.php b/app/Service/common/JWTService.php index b314633d..db29bc40 100755 --- a/app/Service/common/JWTService.php +++ b/app/Service/common/JWTService.php @@ -6,13 +6,29 @@ use Firebase\JWT\JWT; use Firebase\JWT\Key; use Exception; +/** + * JWT 签发与解析服务 + * firebase/php-jwt 对 HS256 要求密钥至少 256 bit(32 字节),过短会抛 Provided key is too short + */ class JWTService { private static mixed $_instance; - private string $secretKey = 'cc_spa_jwt_secret_key'; // 请替换为你的密钥 - + private string $secretKey; private string $token; + /** + * 构造时从配置读取密钥,并兜底保证满足 HS256 最小长度 + */ + public function __construct() + { + // 优先读环境变量 JWT_SECRET;长度不足时用 hash 派生,避免库直接报错 + $secret = (string) config('nl.jwt.secret', ''); + if (strlen($secret) < 32) { + $secret = hash('sha256', $secret !== '' ? $secret : 'nl_admin_jwt_fallback_secret'); + } + $this->secretKey = $secret; + } + /** * 获取实例 * @return null|static diff --git a/config/nl.php b/config/nl.php index 693e25e2..47e06a66 100755 --- a/config/nl.php +++ b/config/nl.php @@ -18,6 +18,12 @@ return [ // 'over_time' => 0 //处方审核自动失效时间 ], ], + /* + * JWT 配置(HS256 密钥至少 32 字节,否则 firebase/php-jwt 报 Provided key is too short) + */ + 'jwt' => [ + 'secret' => env('JWT_SECRET', 'nl_admin_jwt_secret_key_change_me_32b'), + ], /* * redis配置 */