Laravel 8 JWT 登录返回 401 的根本原因与解决方案

3次阅读

Laravel 8 JWT 登录返回 401 的根本原因与解决方案

laravel 8 中使用 tymon/jwt-auth 登录时持续返回 401 错误,通常并非配置或代码逻辑问题,而是用户密码未按 laravel 默认的 bcrypt 格式加密所致——这是 jwt 认证失败最常见的底层原因。

在 Laravel 中,Auth::attempt() 及其封装方法(如 JWTGuard::attempt())严格依赖 Hash::check() 进行密码比对,而该方法仅原生支持 Laravel 默认的 bcrypt 哈希算法。若数据库中用户密码是通过 md5、sha1 或其他非标准方式存储的(例如从旧系统迁移、手动插入或前端传参误处理),$this->guard()->attempt($credentials) 将始终返回 false,最终触发 401 响应:

// AuthController.php 中关键逻辑(已正确配置) public function login(Request $request) {     $credentials = $request->only('email', 'password');      // ⚠️ 此处失败:即使 email 正确,bcrypt 不匹配 → attempt() 返回 false     if (! $token = $this->guard()->attempt($credentials)) {         return response()->json(['error' => 'Email or Password invalid'], 401);     }      return $this->respondWithToken($token); }

验证与修复步骤:

  1. 检查数据库密码字段值
    查看 users 表中目标用户的 password 字段是否以 $2y$、$2a$ 或 $2b$ 开头(bcrypt 标准前缀)。例如:

    $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi  ← 合法 bcrypt 5f4dcc3b5aa765d61d8327deb882cf99                                    ← md5 ❌
  2. 确保用户注册/密码重置流程使用 Hash::make()
    创建或更新用户时,必须调用 Laravel 的哈希服务:

    use IlluminateSupportFacadesHash;  // ✅ 正确:自动使用 bcrypt $user = User::create([     'name' => 'John',     'email' => 'john@example.com',     'password' => Hash::make('plain-password'), // 关键! ]);
  3. 批量修复已有错误密码(如需迁移)
    若历史数据含 md5 密码,不可直接替换为 bcrypt(因原始明文已丢失),应引导用户重置密码;或在首次登录时捕获 401 并触发平滑升级:

    // 进阶:兼容旧密码并自动升级(仅限可信场景) public function login(Request $request) {     $credentials = $request->only('email', 'password');     $user = User::where('email', $credentials['email'])->first();      if ($user && !Hash::check($credentials['password'], $user->password)) {         // 检查是否为旧 md5 密码(示例逻辑,实际需更严谨校验)         if (strlen($user->password) === 32 && ctype_xdigit($user->password)) {             if (md5($credentials['password']) === $user->password) {                 // 升级为 bcrypt 并重新尝试认证                 $user->password = Hash::make($credentials['password']);                 $user->save();                 $credentials['password'] = $user->password; // 重置凭据             }         }     }      if (!$token = $this->guard()->attempt($credentials)) {         return response()->json(['error' => 'Unauthorized'], 401);     }      return $this->respondWithToken($token); }

⚠️ 其他必要检查项(排除干扰因素):

  • 确认 config/auth.php 中 guards.api.driver 已设为 ‘jwt’,且 providers.users.model 指向正确实现 JWTSubject 的 User 类;
  • 验证 .env 中 JWT_SECRET 已通过 php artisan jwt:secret 生成,且未被意外覆盖;
  • 使用 postman 时,确保请求头 Content-Type: application/json,且 JSON Body 正确传递 “email” 和 “password” 字段(无多余空格或编码错误);
  • 检查 User 模型是否真正继承 Authenticatable 并启用 Notifiable(虽非 JWT 必需,但缺失可能引发隐式异常)。

总结:401 不是 JWT 配置失败的信号,而是 Laravel 认证层在密码校验阶段就已拒绝。始终以 bcrypt 为唯一可信密码格式,是保障 tymon/jwt-auth 在 Laravel 8 中稳定工作的基石。

text=ZqhQzanResources