使用API Authentication的Laravel 8中的REST-API。
简介
我有Analytics
模型可验证,可以在Web中对请求进行身份验证,而不是使用带有相应User
和analytics
表表的默认user
模型。我已经迁移了api_token
表中的analytics
字段。但是,在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
模型是可认证的。虽然我在api_token
表中有analytics
字段
请求:
我正在端点上发送GET
HTTP请求实例
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 Illuminate\Notifications\Notifiable;
use Notification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notifications\AnalyticsResetPassword;
use Illuminate\Database\Eloquent\Model;
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 Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password', ];
protected $hidden = ['password', 'remember_token',];
protected $casts = ['email_verified_at' => 'datetime',];
}
guard
配置文件中的provider
和config/auth.php
数组:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'analytics' => [
'driver' => 'session',
'provider' => 'analytics',
],
'api' => [
'driver' => 'token',
'provider' => 'user',
'hash' => true,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'analytics' => [
'driver' => 'eloquent',
'model' => App\Analytics::class,
],
],
Controller中的令牌生成方法
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);
}