Answer the question
In order to leave comments, you need to log in
Why doesn't RBAC work in Yii2?
Hey!
Actually a question. Create role, create permission, attach permission to role. I add a role to the user.
But for some reason the user with such access role does not receive.
How:
$auth = \Yii::$app->authManager;
$admin = $auth->createRole('admin');
$auth->add($admin);
$showFilter = $auth->createPermission('showFilter');
$showFilter->description = "Показать фильтр";
$auth->add($showFilter);
$auth->addChild($admin, $showFilter);
$auth->assign($admin, 76);
Yii::$app->user->can('showFilter')
Yii::$app->user->can('admin')
Answer the question
In order to leave comments, you need to log in
You may have RBAC cache enabled, look for the string " 'authManager' => [ " in your project if it looks like this:
'authManager' => [
'class' => 'yii\rbac\DbManager',
'cache' => 'cache'
],
Yii::$app->authManager->invalidateCache();
I understand that the topic is old, but for beginners like me, it is still relevant. In my case, the problem was that, along with the creation of roles and privileges, I immediately tried to screw in the rules, in which I messed up from the very beginning and forgot about them. As soon as I commented out the rules (ruls) - everything worked.
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
use common\components\rbac\UserRoleRule;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
$auth->removeAll(); //delete old data
//Let's create, for example, permissions to access the admin panel
// add "enterInFrontend" permission
$enterInFrontend = $auth->createPermission('enterInFrontend');
$enterInFrontend->description = 'Entering frontend';
$auth->add($enterInFrontend);
// add "enterInBackend" permission
$enterInBackend = $auth->createPermission('enterInBackend');
$enterInBackend->description = 'Admin Login';
$auth->add($enterInBackend);
// add "adminControl" permission
$adminControl = $auth->createPermission('adminControl');
$adminControl->description = 'Moderator control';
$auth-> add($adminControl);
// Turn on our handler
// $rule = new UserRoleRule();
// $auth->add($rule);
//Add roles
$simpleUser = $auth->createRole('simpleUser');
$simpleUser->description = 'role: User';
$auth->add($simpleUser);
$moder = $auth->createRole('moder');
$moder->description = 'role: Moderator';
$auth->add($moder);
$admin = $auth->createRole('admin');
$admin->description = 'role: Administrator';
$auth->add($admin);
//Add children
$auth->addChild($simpleUser, $enterInFrontend);
$auth->addChild($moder, $enterInBackend);
$auth->addChild($admin, $adminControl);
$auth->addChild($moder, $simpleUser);
$auth->addChild($admin, $moder);
}
Mindfulness is our everything!
Now we will understand why rules are needed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question