如何修复错误InvalidArgumentException:未定义Auth-guard[customers].JWT



jwt在api中登录时出错。。当我注册它的善意,但在登录显示错误

InvalidArgumentException:未定义Auth-guard〔customers〕。在里面文件C:\Users\Ahmed\Desktop\projectweb\laavel_pro\vendor\laavel\framework\src\Illuminate\Auth\AuthManager.php在线84

这是控制器

public function login(Request $request){
$credentials = $request->only('email', 'password');
if (Auth::guard('customer')->attempt($credentials))
{
$user= JWTAuth::guard('customer')->user(); 
$jwt = JwtAuth::generateToken($user);
return response()->json(compact('jwt'));
}else{
return response()->json(['error' => 'invalid_credentials'], 400);
}

这是api路由

Route::post('login','UserController@login');

这是auth.php

'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'customer'=>[
'driver' => 'token',
'provider'=> 'customers',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppUser::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => AppCustomer::class,
],

请任何人帮我找到解决方案。。谢谢

首先将警卫的drivertoken更改为session,然后运行以下命令

php artisan cache:clear
php artisan config:cache

首先猜测:在config/auth.php中,所需保护的驱动程序应该是'jwt'而不是'token',因为'token'driver针对用户表中的固定哈希工作,而jwt是不稳定的,不会查询数据库来确定用户。

再次猜测:您对"内部用户"('api'保护(和"客户用户"(应使用'customer'保护(使用相同的控制器。这令人困惑。你在哪里辨别用户类型?

关于错误

未定义Auth-guard〔customers〕。

检查它是否是一个拼写错误,并且您总是将其称为"客户",因为"客户s"不是一个守护者,而是一个提供者。例如,检查路由中间件(例如Route::['middleware'=>'auth:customer']


话虽如此

我猜您安装了tymondsignes/jwt-auth,其配置指南指向了一个场景,在该场景中,您可以替换api防护程序来使用,因此,在该假设下,请确保您已经实现了以下修改:

  1. 如果使用Laravel 5.4或更低版本,则需要执行以下步骤。在较新版本上,它们是为您处理的,因此您可以跳过此步骤

  2. 如上所述,在config/auth.php中,所需保护的驱动程序应该是'jwt',而不是'token',因为'token'driver针对用户表中的固定哈希工作,而jwt是不稳定的,不会查询数据库来确定用户。

  3. 您需要在Customer模型上实现JWTSubject接口(只需添加内容,不需要接触其他方法(

    使用Tymon\JWTAuth\Contracts\JWTSubject;

    类Customer扩展Authenticatable实现JWTSubject{

    /**
    * Get the identifier that will be stored in the subject claim of the JWT.
    *
    * @return mixed
    */
    public function getJWTIdentifier()
    {
    return $this->getKey();
    }
    /**
    * Return a key value array, containing any custom claims 
    * to be added to the JWT.
    *
    * @return array
    */
    public function getJWTCustomClaims()
    { 
    // just an example here, change it to whatever you want
    return [
    'picture' => 'picture', // array values are the fieldname in the DB
    'twitter' => 'twitter_url' 
    ];
    }
    ...
    
  4. 您的控制器应该在构造函数中实现相应的保护,并且将登录方法列入白名单,因为传入标头中没有JWT。

    //用户控制器公共函数__construct(({$this->中间件('auth:users',['except'=>['login']](;}

    公共函数login(({$credentials=请求(['email','password'](;//尝试返回令牌if(!$token=auth((->尝试($credentials(({return response((->json(['error'=>'Unauthorized'],401(;}return response((->json(['access_token'=>$token,'token_type'=>'bearer','expires_in'=>auth((->factory((->getTTL((*60]);}…其他方法。。。

我会先放弃显而易见的:

  • 你还能以用户身份登录吗(api卫士(?如果你这样做了,试着把驱动程序改为"jwt">

最新更新