RequestGuard ::尝试不存在

时间:2018-03-23 05:38:11

标签: laravel laravel-5 laravel-4 laravel-5.2 laravel-5.1

当我登录管理员时,我正在为api尝试multiguard身份验证 跟随错误

  

BadMethodCallException   方法照亮\ Auth \ Req   uestGuard ::尝试不存在。

这是我在控制器中的登录方法

 public function login(Request $request){
    if(Auth::guard('admin-api')->attempt(['email' => request('email'), 'password' => request('password')]))
    {

  // if successful, then redirect to their intended location


        $user = Auth::guard('admin-api');
        $success['token'] =  $user->createToken('admin')->accessToken;
        return response()->json(['success' => $success], $this->successStatus);
    }
    else{
        return response()->json(['error'=>'Unauthorised'], 401);
    }
}

我的api.php

Route::prefix('admin')->group(function () {


Route::post('login', 'API\Admin\AdminController@login')->name('admin.login');
Route::post('register', 'API\Admin\AdminController@register')->name('admin.register');

Route::group(['middleware' => 'auth:admin-api'], function(){
 Route::post('get-details', 'API\Admin\AdminController@getDetails');
});


});

我的管理模式

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class Admin extends Authenticatable
{
 use HasApiTokens, Notifiable;
 protected $table = 'admin';
 protected $guard = 'admin-api';
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

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

}

请告诉我您想要的任何其他输入

3 个答案:

答案 0 :(得分:1)

这是一个更好的技巧

bool

答案 1 :(得分:0)

不幸的是,Laravel Facade for Auth并不期望您将它用于api防护,因为会话和cookie将被设置,因此不支持->attempt()功能。但API中间件会禁用会话和cookie,因为它是无状态的。所以这是黑客。 转到你的confi \ auth并为你的api guard创建一个类似的web实例

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

    'drivers-web' => [
        'driver' => 'session',
        'provider' => 'drivers',
    ],

    'api' => [
        'driver' => 'passport',//previously "token"
        'provider' => 'users',//This will be switched regularly from the middleware between drivers and users
    ],

    'drivers-api' => [
        'driver' => 'passport',//previously "token"
        'provider' => 'drivers',
    ],
],

从不如此,您可以使用护照生成客户端访问令牌,这些令牌是无状态会话。并且还可以很好地进行身份验证。

答案 2 :(得分:0)

对我来说,我将网络驱动程序从护照更改为会话。 Laravel的缓存必须清除才能返回会话驱动程序

php artisan cache:clear