Laravel 5.3 中的多重身份验证 [英] Multiple Authentication in Laravel 5.3

查看:31
本文介绍了Laravel 5.3 中的多重身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Laravel 5.3 中为两个不同的表(用户和管理员)设置多重身份验证.

How to setup multiple authentication in Laravel 5.3 for two different tables(Users and Admin).

默认 Laravel 有用户模型.

By default Laravel has User Model.

推荐答案

看起来你需要实现角色.您可以使用默认的 Laravel 用户模型,并且需要创建一个角色模型:

Looks like you need to implements roles. You can use the default Laravel User Model and will need to create a Role Model:

用户模型

...
public function role() {
    return $this->belongsToMany('AppUser', 'user_roles', 'role_id', 'user_id');
}

public function inRole($role) {
    return (bool) $this->role()->where('name', '=', $role)->count();
}
...

榜样

...
public function users() {
    return $this->belongsToMany('AppRole', 'user_roles', 'user_id', 'role_id');
}
...

除了用户表之外,您还需要创建 2 个表:

You gonna need to create 2 tables in addition to your users table:

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

现在您可以为您拥有的不同角色实施不同的权限.您可以使用 Policies 或 Gates 定义权限.有关如何执行此操作的更多信息,请查看文档.

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.

现在要将您的成员重定向到/users/home 并将管理员重定向到/admin/dashboard,您可以执行以下操作:

Now to redirect your members to /users/home and admins to /admin/dashboard you can do the following:

您在 AuthServiceProvider 中定义了 adminAccess:

You define adminAccess in your AuthServiceProvider:

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('/');
}

然后在您的 Kernal.php 中的 $routeMiddleware 变量中注册中间件.然后您可以将所有管理路由放在一个组中并在那里使用中间件:

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:

Route::group(['middleware' => 'auth']) {
    // Define your routes
}

这篇关于Laravel 5.3 中的多重身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆