需求:后台有两种权限+管理员+用户
区别:可以访问的页面不同
解决方法:用户表添加role字段,使用到的是yii2 存取控制过滤器(ACF)方法.
>1在web.php中配置授权的类,有两种,我用到的是PhpManager
‘components‘ => [ ‘authManager‘ => [ ‘class‘ => ‘yii\rbac\PhpManager‘, ], ],
>2在用户表中配置角色权限对应的role值,也可以不配置
const ROLE_ADMIN = 0; const ROLE_USER = 1;
>3重写授权规则类AccessRule
class AccessRule extends \yii\filters\AccessRule { /** * @inheritdoc */ protected function matchRole($user) { if (count($this->roles) === 0) { return true; } foreach ($this->roles as $role) { if ($role === ‘?‘) { if ($user->getIsGuest()) { return true; } }elseif (!$user->getIsGuest() && $role == $user->identity->role) { return true; } } return false; } }
>4在控制器中配置相应的权限.
注意其中的ruleConfig是我们刚才改写的类,如果需要控指定的action,则在rules对[action]进行配置.
public function behaviors() { return [ ‘access‘ => [ ‘class‘ => AccessControl::className(), ‘ruleConfig‘ => [ ‘class‘ => AccessRule::className(), ], ‘rules‘ => [ [ ‘allow‘ => true, ‘roles‘ => [ User::ROLE_ADMIN, ], ], ], ], ]; }
时间: 2024-10-08 14:07:57