You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用php-open-source-saver/jwt-auth生成Token时密钥长度不足求助

Laravel中使用php-open-source-saver/jwt-auth生成JWT Token时的密钥长度问题

问题概述

在Laravel项目中使用php-open-source-saver/jwt-auth包实现JWT认证,配置JWT_ALGO=HS256,但生成Token时触发以下错误:

PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException: Could not create token: Key provided is shorter than 256 bits, only 224 bits provided

相关代码

try {
    $notActivated = $this->auth->login($credentials);

    if ($notActivated === trans('user::users.account not validated')) {
        return response()->json(
            [
                'success' => false,
                'message' => trans('user::users.account not validated'),
            ],
            403
        );
    }
    if (!$token = auth('api')->attempt($credentials)) {
        // attempt to verify the credentials and create a token for the user
        return response()->json(
            [
                'success' => false,
                'message' => trans('invalid credentials'),
            ],
            401
        );
    }
}

堆栈跟踪

PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException {#969
#message: "Could not create token: Key provided is shorter than 256 bits, only 224 bits provided"
#code: 0
#file: "Project/vendor/php-open-source-saver/jwt-auth/src/Providers/JWT/Lcobucci.php"
#line: 143
-previous: Lcobucci\JWT\Signer\InvalidKeyProvided {#968
#message: "Key provided is shorter than 256 bits, only 224 bits provided"
#code: 0
#file: "Project/vendor/lcobucci/jwt/src/Signer/InvalidKeyProvided.php"
#line: 39
trace: {
Project/vendor/lcobucci/jwt/src/Signer/InvalidKeyProvided.php:39 {
Lcobucci\JWT\Signer\InvalidKeyProvided::tooShort(int $expectedLength, int $actualLength): self …
› {
› return new self('Key provided is shorter than ' . $expectedLength . ' bits, only ' . $actualLength . ' bits provided');
}
Project/vendor/lcobucci/jwt/src/Signer/Hmac.php:20 {
Lcobucci\JWT\Signer\Hmac->sign(string $payload, Key $key): string …
› if ($actualKeyLength < $expectedKeyLength) {
› throw InvalidKeyProvided::tooShort($expectedKeyLength, $actualKeyLength);
› }
}
Project/vendor/lcobucci/jwt/src/Token/Builder.php:119 {
Lcobucci\JWT\Token\Builder->getToken(Signer $signer, Key $key): Plain …
›
› $signature = $signer->sign($encodedHeaders . '.' . $encodedClaims, $key);
› $encodedSignature = $this->encoder->base64UrlEncode($signature);
}
Project/vendor/php-open-source-saver/jwt-auth/src/Providers/JWT/Lcobucci.php:141 {
PHPOpenSourceSaver\JWTAuth\Providers\JWT\Lcobucci->encode(array $payload) …
›
› return $this->builder->getToken($this->config->signer(), $this->config->signingKey())->toString();
› } catch (Exception $e) {
}
Project/vendor/php-open-source-saver/jwt-auth/src/Manager.php:85 {
PHPOpenSourceSaver\JWTAuth\Manager->encode(Payload $payload) …
› {
› $token = $this->provider->encode($payload->get());
›
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWT.php:74 {
PHPOpenSourceSaver\JWTAuth\JWT->fromSubject(JWTSubject $subject) …
›
› return $this->manager->encode($payload)->get();
› }
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWT.php:84 {
PHPOpenSourceSaver\JWTAuth\JWT->fromUser(JWTSubject $user) …
› {
› return $this->fromSubject($user);
› }
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWTGuard.php:164 {
PHPOpenSourceSaver\JWTAuth\JWTGuard->login(JWTSubject $user) …
› {
› $token = $this->jwt->fromUser($user);
› $this->setToken($token)->setUser($user);
}
Project/vendor/php-open-source-saver/jwt-auth/src/JWTGuard.php:149 {
PHPOpenSourceSaver\JWTAuth\JWTGuard->attempt(array $credentials = [], $login = true) …
› if ($this->hasValidCredentials($user, $credentials)) {
› return $login ? $this->login($user) : true;
› }
}
Project/Modules/User/Http/Controllers/Api/AuthController.php:85 {
Modules\User\Http\Controllers\Api\AuthController->postLogin(ApiLoginRequest $request): JsonResponse …
› }
› if (!$token = auth('api')->attempt($credentials)) {
› // attempt to verify the credentials and create a token for the user
}

已尝试的操作

  • 清除缓存
  • 清除JWT密钥
  • 使用jwt:generate-certs重新生成JWT密钥
  • 手动生成新密钥

解决方向建议

  1. 使用正确的密钥生成命令:HS256是对称加密算法,不需要证书,应执行php artisan jwt:secret生成符合要求的对称密钥,而非用于非对称加密的jwt:generate-certs命令。

  2. 验证密钥长度:HS256要求密钥长度为256位(即32字节,对应32个ASCII字符或44字符的base64编码字符串)。可在Laravel Tinker中执行以下命令检查当前密钥的实际比特长度:

    // 检查JWT_SECRET的比特长度
    strlen(base64_decode(env('JWT_SECRET', ''))) * 8;
    // 若使用APP_KEY作为JWT密钥,检查APP_KEY的实际比特长度
    strlen(base64_decode(str_replace('base64:', '', env('APP_KEY', '')))) * 8;
    

    确保结果为256,若不足则重新生成符合长度要求的密钥。

  3. 确认配置指向正确:检查config/jwt.php中的secret配置项,确保其正确读取.env中的JWT_SECRET变量,无硬编码的短密钥。

  4. 彻底清除配置缓存:执行以下命令确保新密钥生效:

    php artisan config:clear
    php artisan cache:clear
    
  5. 检查APP_KEY有效性:若项目使用Laravel的APP_KEY作为JWT密钥,需确认APP_KEY是通过php artisan key:generate生成的标准32字节base64编码字符串,而非自定义的短密钥。

内容的提问来源于stack exchange,提问作者Samuel Aramide

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 13:27:34