我试图在我的Yii2高级应用程序中使用DBManager实现RBAC。 我已经在几个来源中阅读了RBAC并在https://yii2-cookbook.readthedocs.io/security-rbac/中实现了RBAC,但它并不起作用。这是我的代码。
在common / config
下的main.php中 return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
],
];
在控制台/控制器下的RbacController.php中
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller {
public function actionAssign($role, $username) {
$user = User::find()->where(['username' => $username])->one();
if (!$user) {
throw new InvalidParamException("There is no user \"$username\".");
}
$auth = Yii::$app->authManager;
$asrole = $auth->getRole($role);
if (!$asrole) {
throw new InvalidParamException("There is no role \"$role\".");
}
$auth->assign($asrole, $user->id);
}
}
迁移文件
use yii\db\Migration;
class m160616_092939_rbac_init extends Migration
{
public function up()
{
$auth = Yii::$app->authManager;
//add permission
$manageGivenTable = $auth->createPermission('manageGivenTable');
$manageGivenTable->description = 'Manage and Generate Given Table ';
$auth->add($manageGivenTable);
//add permission
$manageUsers = $auth->createPermission('manageUsers');
$manageUsers->description = 'Manage users';
$auth->add($manageUsers);
//add role. dan ngasih tahu kalau yang tergabung di sbr dapat memanage given tabel
$sbr = $auth->createRole('sbr');
$sbr->description = 'Tim SBR BPS HQ';
$auth->add($sbr);
$auth->addChild($sbr, $manageGivenTable);
//add role dan ngasih tahu kalau admin dapat memanage user dan sekaligus mewarisi sifat-sifat sbr
$admin = $auth->createRole('admin');
$admin->description = 'Web Administrator, Editor, and Developer';
$auth->add($admin);
$auth->addChild($admin, $sbr);
$auth->addChild($admin, $manageUsers);
}
我在关于页面的尝试。在控制器文件中,我添加
'actions' => ['about'],
'allow' => true,
'roles' => ['manageUsers'],
注意:可能需要此信息
yii rbac/assign admin adminname
将来,我想通过管理面板分配用户角色。
答案 0 :(得分:0)
该角色似乎没有分配。尝试添加此
try {
$info = $auth->assign($asrole, $user->id);
VarDumper::dumpAsString("Role has been assigned ".$info);
} catch (Excpetion $e) {
VarDumper::dumpAsString("Exception:".$e);
}
答案 1 :(得分:0)
在RbacController.php中添加
use common\models\User;
它工作正常。