b24*_*b24 9 php rbac yii yii-extensions yii2
我想学习Yii2成员资格并使用Yii来使用数据库存储和检索角色.
我已阅读安全授权以及如何向用户添加角色?并且有人有Rbac的工作示例吗?并尝试使用yii2-admin扩展并尝试了解Yii如何管理用户角色,但我找不到任何工作样本或简单的分步示例.
请指导我并告诉我最简单的解决方案.
Den*_*G B 17
实现基于角色的访问控制是一个非常简单的过程,您甚至可以根据需要从数据库加载角色.
步骤1:在数据库中创建必要的表[您还可以使用console命令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;
Run Code Online (Sandbox Code Playgroud)
第2步:设置配置文件
现在您可以设置配置文件以使用authmanager作为DbManager.这是通过将以下行添加到配置文件的组件部分来完成的
'authManager' => [
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['guest'],
],
Run Code Online (Sandbox Code Playgroud)
第3步:添加和分配角色.
现在,只需将以下代码写入相应的控制器即可添加角色.
use yii\rbac\DbManager;
$r=new DbManager;
$r->init();
$test = $r->createRole('test');
$r->add($test);
Run Code Online (Sandbox Code Playgroud)
您可以通过分配给用户
$r->assign($test, 2);
Run Code Online (Sandbox Code Playgroud)
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',
],
// ...
],
Run Code Online (Sandbox Code Playgroud)
].
然后执行迁移:
yii migrate --migrationPath=@yii/rbac/migrations
Run Code Online (Sandbox Code Playgroud)
它将自动创建数据库中的必需表.现在您可以通过访问AuthManager
yii migrate --migrationPath=@yii/rbac/migrations