web-dev-qa-db-ja.com

rbacとデータベースストレージを使用したYii2ロール管理

Yii2メンバーシップを学び、Yiiを使用して、データベースを使用してロールを保存および取得したいと思います。

セキュリティ認証ユーザーにロールを追加する方法は?Rbacの実用的な例はありますか? を読み、-を使用してみます yii2-admin 拡張機能で、Yiiがユーザーロールを管理する方法を理解しようとしましたが、実用的なサンプルや簡単なステップバイステップの例が見つかりません。

私を導き、最も簡単な解決策を教えてください。

9
b24

ロールベースのアクセス制御の実装は非常に簡単なプロセスであり、必要に応じてデータベースからロールをロードすることもできます。

ステップ1:データベースに必要なテーブルを作成する[ステップ1の代わりにコンソールコマンドyii migrateを使用して移行を適用することもできます]

最初のステップは、データベースに必要なテーブルを作成することです。以下は、データベースで実行する必要のある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

17
Dency G B

公式ドキュメントからの更新されたリンク: 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

5
JJPunch