我想学习Yii成员资格,并使用Yii来存储和检索数据库中的角色。
我已经阅读了安全授权和如何向用户添加角色?有人有Rbac的工作例子吗?并尝试使用yii2-admin扩展,并试图了解Yii如何管理用户角色,但我找不到任何工作样本或简单的一步一步的例子。
请指导我,告诉我最简单的解决方法。
实现基于角色的访问控制是一个非常简单的过程,如果你愿意,你甚至可以从数据库中加载你的角色。
步骤1:在数据库中创建必要的表[您也可以使用控制台命令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;
步骤2:设置配置文件
现在您可以设置配置文件以使用authmanager作为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/-指导-安全- 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