Laravel 5 基于角色的访问控制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32543263/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:20:16  来源:igfitidea点击:

Laravel 5 role based access control

phplaravellaravel-5laravel-5.1rbac

提问by imperium2335

I am trying to come up with an efficient and flexible RBAC solution for my app. I have done a little research and think I have created the following.

我正在尝试为我的应用程序提出一个高效且灵活的 RBAC 解决方案。我做了一些研究,并认为我已经创建了以下内容。

In my User model I have:

在我的用户模型中,我有:

...
public function role() {
        return $this->belongsToMany('App\Models\Role', 'user_roles');
    }

    public function hasRole($role) {
        if($this->role->where('name', $role)->first())
            return true;
    }
...

And an example of usage:

以及一个使用示例:

Route::group(['middleware' => 'auth'], function () {

    Route::get('/dashboard', function () {
        if (Auth::user()->hasRole('Sales')) {
            return view('dashboards/sales');
        } else {
            return 'Don\'t know where to send you :(';
        }
    });

});

Permissions are assigned to roles, but permissions are not checked in the example above. Roles are then assigned to users and a user can have many roles.

权限被分配给角色,但在上面的例子中没有检查权限。然后将角色分配给用户,一个用户可以拥有多个角色。

Is the way I have done things scaleable and an effective RBAC solution?

我做事的方式是否具有可扩展性和有效的 RBAC 解决方案?

回答by AndreL

I've made some RBACapps, and it depends on kind of challange are you facing, e.g.

我制作了一些RBAC应用程序,这取决于您面临的挑战类型,例如

User have a role but you want a that a specific user have access to some area, like Posts, now user can edit posts like a Moderator. The permissions approach in this case suits better than just a role approach.

用户有一个角色,但您希望特定用户可以访问某个区域,例如Posts,现在用户可以像版主一样编辑帖子。在这种情况下,权限方法比角色方法更适合。

Define access by a slug, the other fields can be used as a reference to Super Admin, or ironically for a Editor Role, starting now, a Editor Role plus Permission to a new "area".

通过 slug 定义访问权限,其他字段可以用作对Super Admin的引用,或者讽刺的是,对于Editor Role,从现在开始,一个 Editor Role 加上对新“区域”的权限。

public function up()
{
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name');
        $table->string('slug')->unique();
        $table->string('description')->nullable();
        $table->string('model')->nullable();
    });
}

As example of content data,

作为内容数据的例子,

$createUsersPermission = Permission::create([
    'name' => 'Create permissions',
    'slug' => 'create.permissions',
    ...
]); 

And a example of usage:

以及一个使用示例:

if ($user->can('create.permissions') { // you can pass an id or slug
    //
}

Personally preference, and never used Zizaco Entrustas suggested by the other folks, but it works in the same way. Also you have levels approach too.

个人偏好,从来没有像其他人建议的那样使用Zizaco Entrust,但它的工作方式相同。你也有水平方法。

回答by 89n3ur0n

I did a little different, I made hasRole in UserRole , not is User(does not impact too much but as per code it should be). So Here is my route :

我做了一点不同,我在 UserRole 中创建了 hasRole ,而不是 User (不会影响太大,但按照代码应该是)。所以这是我的路线:

Route::group(['middleware' => 'auth'], function () {
Route::get('/myProfile', function () {
    if (App\UserRole::hasRole('ROLE_CUSTOMER',Auth::user())) {
        return view('views/customer');
    } else {
        return 'Don\'t know where to send you :(';
    }
}); });

Next Thing is, the method in my UserRole. I tried to keep it simple:

接下来是我的 UserRole 中的方法。我试图保持简单:

public static function hasRole($authority,$user) {
        $role = Role::where('authority',$authority)->first();
        $userRole = UserRole::where('role_id',$role->id)
                    ->where('user_id',$user->id)->first();
        if($userRole){
            return true;
        }
    }

We look for the authority(ROLE_USER, ROLE_CUSTOMER etc) and $user is User Object retrieved from DB . Everything else runs as per your question/ Hope it helps! Cheers!

我们查找权限(ROLE_USER、ROLE_CUSTOMER 等),$user 是从 DB 检索的用户对象。其他一切都按照您的问题运行/希望它有帮助!干杯!

回答by Tushar

As there is not out of box solution available for Role based authentication in laravel. You can create a custom Role table that defines the all possible roles your application can have, and role_user table which contains association of user and roles.

因为在 laravel 中没有可用于基于角色的身份验证的开箱即用解决方案。您可以创建一个自定义 Role 表来定义您的应用程序可以拥有的所有可能的角色,以及包含用户和角色关联的 role_user 表。

You can create methods under your User model to check if user belong to a particular role. Make use of that method to register a new middleware. Middleware can be attache to routes or controllers.

您可以在 User 模型下创建方法来检查用户是否属于特定角色。利用该方法注册一个新的中间件。中间件可以附加到路由或控制器。

Detailed demo is given in this link https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/

此链接中提供了详细的演示 https://www.5balloons.info/user-role-based-authentication-and-access-control-in-laravel/