Laravel 5.3 中的多重身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39543967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple Authentication in Laravel 5.3
提问by Mukul Mantosh
How to setup multiple authentication in Laravel 5.3 for two different tables(Users and Admin).
如何在 Laravel 5.3 中为两个不同的表(用户和管理员)设置多重身份验证。
By default Laravel has User Model.
默认情况下,Laravel 具有用户模型。
回答by Gadzhev
Looks like you need to implements roles. You can use the default Laravel User Model and will need to create a Role Model:
看起来您需要实现角色。您可以使用默认的 Laravel 用户模型,并且需要创建一个角色模型:
User Model
用户模型
...
public function role() {
return $this->belongsToMany('App\User', 'user_roles', 'role_id', 'user_id');
}
public function inRole($role) {
return (bool) $this->role()->where('name', '=', $role)->count();
}
...
Role Model
好榜样
...
public function users() {
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
}
...
You gonna need to create 2 tables in addition to your users table:
除了用户表之外,您还需要创建 2 个表:
Table users
id | name
---------
1 | John
2 | Michael
Table roles
id | name
---------
1 | Admin
2 | Member
Table user_roles
id | user_id | role_id
----------------------
1 | 1 | 1
2 | 2 | 1
Now you can implement different permissions for the different roles you have. You can define the permissions using Policies or Gates. For more info how to do that check the documentation.
现在您可以为您拥有的不同角色实施不同的权限。您可以使用 Policies 或 Gates 定义权限。有关如何执行此操作的更多信息,请查看文档。
Now to redirect your members to /users/home and admins to /admin/dashboard you can do the following:
现在要将您的成员重定向到 /users/home 并将管理员重定向到 /admin/dashboard,您可以执行以下操作:
You define adminAccess in your AuthServiceProvider:
您在 AuthServiceProvider 中定义 adminAccess:
public function boot() {
$this->registerPolicies();
...
// Define adminAccess
Gate::define('adminAccess', function ($user) {
return $user->inRole('admin');
});
}
Update:Now you can protect your admin routes with a Middleware like so:
更新:现在您可以使用中间件保护您的管理路由,如下所示:
public function handle($request, Closure $next) {
if (Auth::check() && Auth::user()->inRole('admin')) {
return $next($request);
}
return redirect('/');
}
Then register the Middleware in your Kernal.php in the $routeMiddleware
variable. Then you can place all your admin routes in a group and use the middleware there:
然后在您的 Kernal.php$routeMiddleware
变量中注册中间件。然后你可以将所有管理路由放在一个组中并在那里使用中间件:
Route::group(['middleware' => 'auth']) {
// Define your routes
}
回答by Hesto
If you need multi auth based on guards, try this package for laravel 5.3 https://github.com/Hesto/multi-auth
如果您需要基于守卫的多重身份验证,请尝试使用 laravel 5.3 这个包https://github.com/Hesto/multi-auth