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

Laravel Fortify自定义认证闭包返回API用户数组报类型错误如何解决

问题解决办法

报错核心原因是Laravel认证体系要求传入登录方法的用户实例必须实现Illuminate\Contracts\Auth\Authenticatable契约,你当前直接返回API返回的用户数组不符合该要求,无需数据库即可解决,步骤如下:

步骤1:创建自定义用户类实现Authenticatable契约

新建app/Models/ApiUser.php文件,代码如下:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\Authenticatable;

class ApiUser implements Authenticatable
{
    protected $attributes = [];

    // 构造方法直接传入API返回的用户数组
    public function __construct(array $userAttributes)
    {
        $this->attributes = $userAttributes;
    }

    // 以下为Authenticatable契约要求实现的方法
    public function getAuthIdentifierName()
    {
        // 对应API返回的用户主键字段名
        return 'userid';
    }

    public function getAuthIdentifier()
    {
        return $this->attributes['userid'];
    }

    // 密码已经通过API校验,该方法无需返回真实密码
    public function getAuthPassword()
    {
        return '';
    }

    // 记住我相关方法,不需要的话保留空实现即可
    public function getRememberToken()
    {
        return $this->attributes['remember_token'] ?? '';
    }

    public function setRememberToken($value)
    {
        $this->attributes['remember_token'] = $value;
    }

    public function getRememberTokenName()
    {
        return 'remember_token';
    }

    // 可自行扩展其他字段的访问方法,比如双因素认证状态
    public function isTwoFactorEnabled(): bool
    {
        return $this->attributes['twoFactorEnabled'] === 'true';
    }
}

步骤2:修改Fortify认证逻辑

修正原有代码的拼写错误(passwprd应为password),并将返回的数组转换为自定义ApiUser实例:

Fortify::authenticateUsing(function (Request $request) {
    if($api->validate($request->username, $request->password)) {
        $userArray = $api->find($request->username);
        // 返回实现了Authenticatable契约的对象而非数组
        return new \App\Models\ApiUser($userArray);
    }
});

可选配置:适配Session用户恢复

如果需要支持从Session中恢复登录用户,修改config/auth.php的用户提供者配置:

'providers' => [
    'users' => [
        'driver' => 'array',
        'model' => App\Models\ApiUser::class,
    ],
],

内容的提问来源于stack exchange,提问作者tews-nees

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:45:07