在Laravel中使用自定义防护进行API身份验证时出现FatalThrowableError

时间:2018-06-27 09:13:30

标签: php laravel-5 laravel-passport api-authorization

每次在自定义保护程序中分别尝试通过FatalThrowableErrorBadMethodCallException驱动程序进行身份验证时,我都会不断收到token异常或passport({{1} }),但是使用会话驱动程序就可以了。我已经按照文档定义了防护措施,但仍然无济于事,我不知道我要去哪里错了

代码

Config \ Auth.php

api-users

AuthController.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [ //<== this is not being used as far as i know
        'driver' => 'token',
        'provider' => 'users',
    ],

    'api-users' => [  //<== I am trying to use this guard 
        'driver' => 'session', //<== session works, token or passport doesn't
        'provider' => 'api-users',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'api-users' => [
        'driver' => 'eloquent',
        'model' => App\Models\ApiUser::class,
    ],
],

Models \ ApiUser.php

class AuthController extends Controller
{
    protected function guard()
    {
        return Auth::guard('api-users');
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt($this->credentials($request), false);
    }

    protected function credentials(Request $request)
    {
        return $request->only('email', 'password');
    }

    public function login(Request $request)
    {
        if ($this->attemptLogin($request)) { //<== this doesn't work with token/passport driver but works with a session driver
            echo 'success';
        } else {
            echo "fail";
        }
    }
}

错误

使用令牌作为驱动程序时

class ApiUser extends Authenticatable
{
    use SoftDeletes;
    use Notifiable;
    use HasApiTokens;

    protected $guard = 'api-users';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'mobile', 'password', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token', 'created_at', 'updated_at', 'deleted_at'];

    /**
     * Type cast the active field
     */
    protected $casts = [
        'active' => 'boolean',
    ];
}

使用护照作为司机时

Call to undefined method Illuminate\Auth\TokenGuard::attempt()

0 个答案:

没有答案