我正在尝试使用基于角色的访问控制在this is the entry for auth_item-basic框架中。
代码如下:
config/web.php:
'authManager' => [
'class' => 'yii\rbac\DbManager',
],控制器:
public function actionCreate()
{
if(Yii::$app->user->can('countries/create')){
$chk = 'Can Do';
}else{
$chk = 'Can Not Do';
}
echo $chk;exit();
}发布于 2020-11-25 18:15:00
请确保检查下面的所有点是否都按预期工作。
该信息来自the Yii2 guide pages,并在那里进行了更详细的解释。
'authManager' => [
'class' => 'yii\rbac\DbManager',
],一种可能是最简单的方法是使用控制台控制器,但然后您必须在代码中的其他位置处理用户创建和更新的权限。
<?php
namespace app\commands;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
$auth->removeAll();
// add "create country" permission better remove '/'
$createCountry = $auth->createPermission('createCountry');
$createCountry->description = 'Create a new country';
$auth->add($createCountry);
// add "admin" role and give this role the "createCountry" permission
$adminRole = $auth->createRole('admin');
$auth->add($adminRole);
$auth->addChild($adminRole, $createCountry);
// Assign roles to user by id, make sure this is the user that you
// are using when testing
$auth->assign($adminRole, 1);
}
}public function actionCreate()
{
// Logs just to find what is wrong, remove them later
if (($user = Yii::$app->user->identity) === null) {
Yii::debug('No user logged in, the problem is there', __METHOD__);
} else {
Yii::debug("User $user->id logged in", __METHOD__);
if (!Yii::$app->user->can('createCountry') {
Yii::debug('User cannot create country', __METHOD__);
if (!Yii::$app->user->can('admin') {
Yii::debug('User does not have admin role', __METHOD__);
} else {
Yii::debug('Admin role does not have createCountry child', __METHOD__);
}
} else {
Yii::debug('User can create country, ALL DONE!', __METHOD__);
}
}
// Remove above this line after finding the problem
// You would keep the logic below this line after finding the problem
if(!Yii::$app->user->can('createCountry')) {
throw new ForbiddenHttpException('You are not allowed to do that');
}
// No 'else' after throwing, more readable code
// Your logic goes here, the user can create countries
}发布于 2020-11-28 22:09:43
我不确定,但我认为:
缺少addChild($adminRole、$createCountry); )的
针对表auth_item_child.检查权限
父子admin 'createCountry‘admin 'deleteCountry’guest 'indexCountry‘....
if(Yii::$app->user->can('createCountry')){
https://stackoverflow.com/questions/64888985
复制相似问题