繁体   English   中英

使用rbac和数据库存储进行Yii2角色管理

[英]Yii2 role management with rbac and database storage

我想学习Yii2成员资格并使用Yii来使用数据库存储和检索角色。

我已阅读安全授权以及如何向用户添加角色? 并且有人有Rbac的工作示例吗? 并尝试使用yii2-admin扩展并尝试了解Yii如何管理用户角色,但我找不到任何工作样本或简单的分步示例。

请指导我并告诉我最简单的解决方案。

实现基于角色的访问控制是一个非常简单的过程,您甚至可以根据需要从数据库加载角色。

步骤1:在数据库中创建必要的表[您还可以使用控制台命令yii migrate而不是步骤1应用迁移]

第一步是在数据库中创建必要的表.Below是您需要在数据库中运行的SQL。

drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;

create table `auth_rule`
(
`name` varchar(64) not null,
`data` text,
`created_at` integer,
`updated_at` integer,
    primary key (`name`)
) engine InnoDB;

create table `auth_item`
(
`name` varchar(64) not null,
`type` integer not null,
`description` text,
`rule_name` varchar(64),
`data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`),
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
key `type` (`type`)
) engine InnoDB;

create table `auth_item_child`
(
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`, `child`),
foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `auth_assignment`
(
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`created_at` integer,
primary key (`item_name`, `user_id`),
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

第2步:设置配置文件

现在您可以设置配置文件以将authmanager用作DbManager 这是通过将以下行添加到配置文件的组件部分来完成的

     'authManager' => [
                           'class' => 'yii\rbac\DbManager',
                           'defaultRoles' => ['guest'],
          ],

第3步:添加和分配角色。

现在,只需将以下代码写入相应的控制器即可添加角色。

    use yii\rbac\DbManager;
    $r=new DbManager;
    $r->init();
    $test = $r->createRole('test');
    $r->add($test);

您可以通过分配给用户

    $r->assign($test, 2);

http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

来自官方文档的更新链接: http//www.yiiframework.com/doc-2.0/guide-security-authorization.html

如果您正在使用数据库,则必须将authmanager添加到应用程序组件:

return [
// ...
'components' => [
    'authManager' => [
        'class' => 'yii\rbac\DbManager',
    ],
    // ...
],

]。

然后执行迁移:

yii migrate --migrationPath=@yii/rbac/migrations

它将自动创建数据库中的必需表。 现在您可以通过访问AuthManager

yii migrate --migrationPath=@yii/rbac/migrations

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM