gpt4 book ai didi

php - 使用 rbac 和数据库存储的 Yii2 角色管理

转载 作者:可可西里 更新时间:2023-10-31 23:03:57 24 4
gpt4 key购买 nike

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

我已阅读 Security AuthorizationHow to add role to user?Does Anyone Have A Working Example Of 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;

第二步:设置配置文件

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

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

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

现在你可以通过在你对应的controller中写入下面的代码来添加角色

    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

关于php - 使用 rbac 和数据库存储的 Yii2 角色管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24554712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com