实施基于角色的访问控制是一个非常简单的过程,您甚至可以根据需要从数据库中加载您的角色。
Step1:在数据库中创建必要的表[您也可以使用控制台命令yii migrate而不是步骤1来应用迁移]
第一步是在数据库中创建必要的表。下面是你需要在数据库中运行的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;
第二步:设置配置文件
现在您可以设置配置文件以将身份验证管理器用作DbManager。这是通过将以下行添加到配置文件的组件部分来完成的
'authManager' => [
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['guest'],
],
Step3:添加和分配角色。
现在您只需将以下代码写入相应的控制器即可添加角色。
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