当我登录管理员时,我正在尝试对 api 进行多重保护身份验证,我得到了以下错误
BadMethodCallException 方法照明\身份验证\请求 uestGuard::try 不存在。
这是我在控制器中的登录方法
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', 'APIAdminAdminController@login')->name('admin.login');
Route::post('register', 'APIAdminAdminController@register')->name('admin.register');
Route::group(['middleware' => 'auth:admin-api'], function(){
Route::post('get-details', 'APIAdminAdminController@getDetails');
});
});
我的管理模型
<?php
namespace App;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
use LaravelPassportHasApiTokens;
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',
];
}
请告诉我您想要的任何其他输入
一个更好的黑客是这个
$credentials = ['email' => $request->username, 'password' => $request->password];
//Since we are not using guard web in API request, we have to add it here (
// guard('web') ) to access the Auth::attempt function,
// the Auth::attempt needs web guard and crsf token, but using it here bypasses
// the post with crsf.
if (Auth::guard('web')->attempt($credentials, false, false)) {
dd('user is OK');
}else{
dd('user is NOT OK');
}
Laravel Facade for Auth 不希望您将其用于 api 保护,因为将设置会话和 cookie,因此不支持->attempt()
功能。但是 API 中间件禁用会话和 cookie,因为它是无状态的。所以这是黑客。获取您的 confi\auth 并为您的 api 守卫创建一个类似的 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',
],
],
无论如何,您可以使用护照生成无状态会话的客户端访问令牌。并且还可以很好地用于身份验证。
您不能使用Auth::guard('admin-api'(->尝试使用带有驱动程序值的警卫是令牌或护照,因此您可以重复保护并使用会话驱动程序制作一个,并使用护照制作第二个,然后您可以使用会话一个来区分其他,您可以从这里
查看参考和源代码https://web-brackets.com/discussion/103/method-illuminate-auth-requestguard-attempt-does-not-exist-
对我来说,我将网络驱动程序从护照更改为会话。必须清除 Laravel 的缓存才能返回到会话驱动程序
php artisan cache:clear