Laravel Passport TokenGuard :: __ construct()必须实现接口

时间:2019-05-31 11:15:13

标签: php laravel rest laravel-passport

我正在使用Laravel和Laravel Passport创建一个REST API。我尝试访问受默认laravel api auth中间件保护的路由:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::prefix('auth')->group(function () {
    Route::post('login', 'Auth\ApiAuthController@login');
});

在请求标头中,我传递了Authorization: Bearer <my_secret_token>,但出现了这个异常:

Argument 1 passed to Illuminate\Auth\TokenGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in /Users/markusheinemann/Projekte/Lycus/application/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 162

这是我的请求标头:

{
  content-type: "application/json",
  x-requested-with: "XMLHttpRequest",
  authorization: "********",
  user-agent: "PostmanRuntime/7.13.0",
  accept: "*/*",
  cache-control: "no-cache",
  postman-token: "ebfa3211-958d-4042-ab6a-a488847fc2f7",
  host: "localhost",
  accept-encoding: "gzip, deflate",
  connection: "keep-alive"
}

这是我的令牌创建过程:

public function login(LoginRequest $request)
{
    $credentials = $request->only(['email', 'password']);

    if(!Auth::attempt($credentials)) {
        return response()->json(['message' => trans('auth.failed')], 401);
    }

    $token = $request->user()->createToken('Lycus Frontend Client');
    $token->token->save();

    return response()->json([
        'accessToken' => $token->accessToken,
        'expiresAt' => $token->token->expires_at,
    ]);
}

有人知道为什么我会收到此错误吗?

1 个答案:

答案 0 :(得分:1)

确保您的用户模型使用:

class User extends Authenticatable 
{ 
    use HasApiTokens; 
}

---编辑----

我已经在互联网上的一些指南中看到了登录代码,我个人认为最好将请求重新发送到Passport API,然后让其登录并创建令牌。

$request->validate([
    'email'    => 'required|string|email',
    'password' => 'required|string'
]);

$http = new Client();

try {
    $response = $http->post('/oauth/token', [
        'form_params' => [
            'grant_type'    => 'password',
            'client_id'     => 2,
            'client_secret' => 'secret_key_from_passport_client',
            'username'      => $request->email,
            'password'      => $request->password,
        ]
    ]);

    return $response->getBody();
} catch (BadResponseException $e) {
    return response()->json([], 422);
}

---编辑--- 如果将用户移动到其他名称空间,请不要忘记在auth.php中进行更改

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

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],