Laravel的多个身份验证 [英] Multiple auth for laravel
问题描述
我想将中间件身份验证分为两个角色,一个角色是管理员,第二个角色是用户 但是某些路由适用于所有用户和管理员,而只有少数路由仅适用于管理员,我该如何拆分路由?
I want to split middleware auth to two role one is for admin and second for user but some route is use for all user and admin and few route is for admin only how can i split with route?
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
//Some route here
});
Route::group(['middleware' => ['guest']], function () {
//some route here
});
推荐答案
这是我对管理员和用户的访问控制的实现(在我的情况下为代理),我的用户表(is_admin
)中有一个布尔字段,普通用户为0,管理员为1.
Here is my implementation for access control for admin and users(agents in my case) I have a boolean field in my user table (is_admin
) which is 0 for normal users and 1 for admins.
在您的用户模型中添加以下内容:
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
为Admin和Agent创建新的中间件:
php artisan make:middleware Admin
php artisan make:middleware Agent
中间件文件将在App\Http\Middleware\
将此内容添加到Admin.php
中的班级:
Add this to class inside Admin.php
:
public function handle($request, Closure $next)
{
if ( Auth::check() && Auth::user()->isAdmin() )
{
return $next($request);
}
return redirect('/agent');
}
将此添加到Agent.php
Add this to Agent.php
public function handle($request, Closure $next)
{
if ( Auth::check() && !Auth::user()->isAdmin() )
{
return $next($request);
}
return redirect('/home');
}
在向laravel注册中间件之后,将其添加到位于app\Http\Kernel.php
After this register your middleware with laravel to do this add this to protected $routeMiddleware
in your Kernel.php
which is located at app\Http\Kernel.php
'admin' => 'App\Http\Middleware\Admin',
'agent' => 'App\Http\Middleware\Agent',
请确保按照中间件文件中所述为重定向创建正确的路由.在此之后,您几乎完成了.现在,要验证用户是管理员还是普通用户,请将其添加到控制器的构造方法中.
Make sure to create proper routes for redirection as we've mentioned in our middleware files. After this you are almost done. Now to verify if a user is admin or normal user add this to the constructor method of your controller.
仅允许管理员用户执行的操作:
public function __construct()
{
$this->middleware('auth');
$this->middleware('admin');
}
仅允许普通(代理)用户执行的操作:
public function __construct() {
$this->middleware('auth');
$this->middleware('agent');
}
或者您也可以在路由中添加中间件
Route::group(['middleware' => 'admin'], function () {
//Some route here
});
这篇关于Laravel的多个身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!