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

Laravel 10中Hash::check()验证密码失败但可正常登录问题

Laravel 10中Hash::check()验证密码失败但登录正常的排查方案

可能的原因及解决步骤

1. 请求参数获取异常

  • 检查前端传入的密码参数是否被正确接收:前端可能存在参数名拼写错误(比如传pwd而非password)、额外空格或特殊字符转义问题。可以在代码中添加日志输出关键数据:
    \Log::info('接收的原始密码:', ['password' => $password]);
    \Log::info('数据库存储的哈希值:', ['hash' => $client?->password]);
    
  • 确认请求的Content-Type是否匹配:表单提交需确保为application/x-www-form-urlencoded,JSON提交需保证Laravel能正确解析请求体。

2. 模型或数据库字段处理问题

  • 检查Client模型是否存在**访问器(Accessor)**篡改了password字段的返回值:如果模型中定义了类似以下代码,会导致拿到的不是数据库原始哈希值,从而验证失败:
    public function getPasswordAttribute($value) {
        // 错误的自定义处理逻辑
        return some_modify_function($value);
    }
    
  • 确认数据库password字段的类型和长度:哈希值通常需要足够长的存储长度(比如varchar(255)),避免截断导致哈希不完整。

3. 哈希算法不一致

  • 查看config/hashing.php中的default配置,确认当前默认哈希驱动与创建用户密码时的驱动一致(默认是bcrypt)。若用户创建时使用了其他驱动(如argon2i),当前配置变更会导致验证失败。
  • 确保用户密码是通过Hash::make()生成的,而非手动存储明文或错误的哈希值。

4. 字符编码或隐式转换问题

  • 检查数据库password字段的字符集是否为utf8mb4,避免特殊字符存储时出现编码转换错误。
  • 验证密码中的特殊字符(如&、=)是否在前端传递时被正确编码,导致后端接收到的密码与用户实际输入不一致。

代码排查优化示例

public function recharge_by_client(Request $request){
    $telf      = $request->telf;
    $password  = $request->password;
    $credit    = $request->credit;

    try {
        $client = Client::where('telf', $telf)->first();
        
        // 新增日志用于排查关键数据
        \Log::info('用户查询结果:', ['client' => $client ? $client->toArray() : null]);
        \Log::info('待验证密码:', ['password' => $password]);
        if ($client) {
            \Log::info('数据库哈希值:', ['hash' => $client->password]);
            $checkResult = Hash::check($password, $client->password);
            \Log::info('密码验证结果:', ['result' => $checkResult]);
        }

        if ($client && Hash::check($password, $client->password)) {
            \Log::info('Entramos a update');
            HomeHelper::recharge_money($client->id, $credit);
        }else{
            \Log::info('NO entramos a update');
            return ['credit_updated' => 0];
        }
    } catch (\Exception $e) {
        \Log::info($e->getMessage());
        return ['credit_updated' => 0];
    }

    return ['credit_updated' => Client::find($client->id)->credit];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:57:03