我的问题很简单,我想在我的laravel应用中使用Guard进行多认证(用户+ admin),因此我可以在控制器中简单地检查经过身份验证的用户是否为admin,例如:
public function addCategories(Request $request) {
if (!Auth::guard('admin')->check()) {
abort(404);
}
....
}
但是上面的代码总是返回false,不知道为什么,这是我的管理员登录名:
public function doLogin(Request $request) {
try {
$validator = \Validator::make($request->post(), [
'username' => array(
'required',
'string',
'max:12',
'regex:/(^[A-Za-z0-9_]+$)+/'
),
'password' => 'required|max:12'
]);
if ($validator->fails()) {
//$validator->errors()
throw new Exception('post data are incorrect');
}
$admin = Admin::where('AUsername', '=', $request->post('username'))
->first();
if ($admin == null) {
throw new Exception('username or password are incorrect');
} else if (!\Hash::check($request->post('password'), $admin->toArray()['APassword'])) {
throw new Exception('username or password are incorrect');
}
Auth::guard('admin')->login($admin);
if (!Auth::guard('admin')->check()) {
throw new Exception('could not login, please try again later');
}
return response()->json([
'success' => 'login success'
]);
} catch(Exception $e) {
return response()->json(
['error' => $e->getMessage()]
);
}
}
通过我不使用的方式(Auth :: attempt()),因为它总是失败(返回false)
最后这是我的auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
答案 0 :(得分:0)
您应该从Authenticateable扩展管理模型,而不是雄辩的模型 并为需要管理员权限的路由调用auth:admin中间件 这个链接也可以帮助您 multi-auth in laravel