gpt4 book ai didi

php - yii2 在后端拒绝用户登录

转载 作者:可可西里 更新时间:2023-11-01 13:40:00 24 4
gpt4 key购买 nike

我有应用了 RBAC 迁移的 yii2 高级模板。我试图学习 RBAC 并遵循了 Docs 2.0 .

我是用数据库登录的,但是前端和后端都是用任意账号登录的。我创建了 2 个 RBAC 角色(管理员、用户),但无法理解或找不到如何操作

restrict back-end to login non-admin user-role.

以下是角色的代码。和数据库条目:

namespace console\controllers;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;

// add "admin" role
$admin = $auth->createRole('admin');
$auth->add($admin);

// add "user" role
$user = $auth->createRole('user');
$auth->add($user);

$auth->assign($admin, 1);
}
}

用户表:

admin   admin@gmail.com     20  10  1421197319  1421197319
user user@gmail.com 10 10 1421198124 1421198124

现行规则:

'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],

最佳答案

已解决 - 注意:解决方案不完全是 RBAC,而是 ACF。

经过查找和咨询,在This yii2viki.找到了解决方案

我不清楚 RBAC 的行为,因为我认为它不会发挥作用在执行某些操作(登录、提交等)之前执行特定任务。

实际上,RBAC 会让你做任何你想做的事,事后检查请求许可,不允许则阻止。

示例

There is some yard sale in a house and you are free to roam around it's front yard. The house gate/entrance doesn't have any guard at front and its not locked. You try to sneak into the house and as soon you get into the house there is some security guard inside who abruptly stops you to identify yourself, he scan your information in the house security system(permissions in DB) and doesn't find your right to be in the house. He forces you out. This guard is RBAC

I needed a guard at the front gate, who won't let anybody in unless they are allowed to. And that would be ACF.

So, now I needed a way to tell the back-end system that a specific role cannot perform a specific action beforehand (i.e. deny non-admin login at back-end), this is not possible with RBAC so, for that we could use 'matchCallback' using ACF.

后端规则:

        'rules' => [
[
'actions' => ['login'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return Yii::$app->user->identity->isAdmin;
}
],
]

True 时 matchCallback 允许执行操作,False 时拒绝操作。 isAdmin是一个getter函数,需要在User模型中定义。

namespace /common/models/User;

const ROLE_ADMIN = 20;
public function getIsAdmin()
{
return $this->role == self::ROLE_ADMIN;
}

我已经在 This yii2 viki's comments. 中发布了模型的完整工作代码

关于php - yii2 在后端拒绝用户登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com