>我有两个用户管理员/用户,我想为 API 验证这两个用户,它适用于一个用户,但不适用于管理员
看看我试过什么在管理控制器中
public function login(Request $request){
// $res=;
// dd ($res);
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password]))
{
// if successful, then redirect to their intended location
$user = auth()->guard('admin')->user();
$success['token'] = $user->createToken('admin')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised','email'=> $request->email,'password'=> $request->password], 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');
});
});
当我尝试为管理员调用尝试函数时,它给了我错误
BadMethodCallException 方法 Illuminate\Auth\RequestGuard::try 不存在。
您能否分享您对如何在拉拉维尔/护照中进行多重身份验证的想法
您可以在Laravel护照中实现Multiauth,您必须按照以下步骤操作
1(在我的情况下创建4个守卫,我创建如下
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
'admin-api' => [
'driver' => 'passport',
'provider' => 'admin',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
然后,在控制器中记录该类型的用户时,请确保您使用的是SESSIO驱动程序保护,例如
用户控制器.php
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
在管理员控制器中.php
public function login(){
if(Auth::guard('admin')->attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::guard('admin')->user();
$success['token'] = $user->createToken('admin')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
检查令牌时,请使用护照驾驶员警卫,例如
public function getDetails()
{
$user = Auth::guard('admin-api')->user();
return response()->json(['success' => $user], $this->successStatus);
}
和中间件
Route::group(['middleware' => 'auth:api'], function(){
Route::post('admin/get-details', 'APIAdminAdminController@getDetails');
});
我设法通过中间件做到了这一点,希望这会对您有所帮助 - 拉拉维尔护照 使用卫兵进行多重身份验证