使用API身份验证的Laravel 8中的REST-API。
简介
我有Analytics
模型Authenticable来在web中验证请求,而不是使用默认的User
模型和相应的analytics
和user
表表。我已经迁移了analytics
表中的api_token
字段。然而,在访问POSTMAN中的API路由时,我得到了以下错误响应。
响应
{
"message": "Argument 1 passed to Illuminate\Auth\TokenGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in source\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 162",
"exception": "TypeError",
}
第162行的source\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
public function createTokenDriver($name, $config)
{
$guard = new TokenGuard(
$this->createUserProvider($config['provider'] ?? null),
$this->app['request'],
$config['input_key'] ?? 'api_token',
$config['storage_key'] ?? 'api_token',
$config['hash'] ?? false // **** This is line 162 **** //
);
我尝试将第162行更改为$config['hash'] ?? true
,但仍然得到相同的错误。
注意:
Analytics
和User
模型是可验证的。而我在analytics
表中有api_token
字段
请求:
我正在端点上发送HTTP请求的GET
实例http://example.com/api/user?api_token=token(this is unhashed token)
以下是以下配置
route/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Analytics
和User
型号如下:
<?php
namespace App;
use IlluminateNotificationsNotifiable;
use Notification;
use IlluminateFoundationAuthUser as Authenticatable;
use AppNotificationsAnalyticsResetPassword;
use IlluminateDatabaseEloquentModel;
class Analytics extends Authenticatable
{
use Notifiable;
public function sendPasswordResetNotification($token)
{
$this->notify(new AnalyticsResetPassword($token));
}
protected $table = "analytics";
protected $fillable = ['name', 'email', 'password', 'mobile', api_token', ];
protected $hidden = ['password', 'api_token', 'remember_token', ];
}
<?php
namespace App;
use IlluminateNotificationsNotifiable;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', ];
protected $hidden = ['password', 'remember_token',];
protected $casts = ['email_verified_at' => 'datetime',];
}
config/auth.php
配置文件中的guard
和provider
阵列:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'analytics' => [
'driver' => 'session',
'provider' => 'analytics',
],
'api' => [
'driver' => 'token',
'provider' => 'user',
'hash' => true,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppUser::class,
],
'analytics' => [
'driver' => 'eloquent',
'model' => AppAnalytics::class,
],
],
控制器中的令牌生成方法
public function token(Request $request)
{
$token = Str::random(60);
$user = Auth::user();
$user->api_token = hash('sha256', $token);
$user->save();
return redirect('/analytics/security')->with('success', 'Token Generated Successfully!')->with("token" , $token);
}
'api' => [
'driver' => 'token',
'provider' => 'user',
'hash' => true,
],
我认为问题出在这个保护配置中的提供者属性上,因为providers
中没有user
的条目——您只有users
和analytics