使用Yii2 RBAC进行Restful API请求

时间:2019-07-25 08:28:44

标签: php rest api yii2 rbac

我开发了一个基于Yii2框架的网络应用程序。该网络应用程序使用RBAC系统进行操作授权,具体取决于用户类型(管理员,员工,子员工)。现在,我正在开发一个移动应用程序,并为该移动应用程序调用的控制器创建了一个新的模块“移动”。在这些新控制器中,我设置了带有CORS和Authenticator的行为功能,并且这些都可以正常工作。我还为网络应用设置了RBAC系统,但在移动模块中不起作用。有人可以帮我设置控制器/操作的授权吗?

public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'except' => ['index','view','test'],
            'authMethods' => [
                HttpBearerAuth::className(),
                HttpBasicAuth::className(),
                // QueryParamAuth::className(),
            ],
        ];

        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);

        $behaviors['corsFilter'] =
        [
            'class' => \yii\filters\Cors::className(),
            'cors' => [
                // restrict access to
                'Origin' => ['*'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
                // // Allow only headers 'X-Wsse'
                'Access-Control-Request-Headers' => ['*'],
                // // Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
                'Access-Control-Allow-Credentials' => false,
                // // Allow OPTIONS caching
                'Access-Control-Max-Age' => 3600,
                // // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],

        ];



        $behaviors['authenticator'] = $auth;
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        // $behaviors['authenticator']['except'] = ['OPTIONS', 'login'];
        $behaviors['access'] = 
        [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['create','view','update','delete','index', 'logout'],
                    'roles' => ['@'],
                    'denyCallback' => function ($rule, $action) {
                        throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page');
                    }
                ],
                [
                    'allow' => true,
                    'actions' => ['login', 'index','test'],
                    'roles' => ['?'],
                    'denyCallback' => function ($rule, $action) {
                        throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page');
                    }
                ],
            ],

        ];

        return $behaviors;
    }

1 个答案:

答案 0 :(得分:0)

覆盖checkAccess()的{​​{1}}方法

ActiveController()不是使用$behaviors['access']时检查访问权限的正确方法,相反,您应该覆盖yii\rest\ActiveController方法。

文档为herehere

操作方法示例:

checkAccess()

查看您的示例,似乎您只是在检查经过身份验证的用户/** * Checks the privilege of the current user. * * This method should be overridden to check whether the current user has the privilege * to run the specified action against the specified data model. * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. * * @param string $action the ID of the action to be executed * @param \yii\base\Model $model the model to be accessed. If `null`, it means no specific model is being accessed. * @param array $params additional parameters * @throws ForbiddenHttpException if the user does not have access */ public function checkAccess($action, $model = null, $params = []) { // You could completely block some actions if ($action === 'delete') { throw new ForbiddenHttpException( Yii::t('app', 'You are not allowed to {action} client models.', ['action' => $action] ) ); } // You could check if the current user has permission to run the action if ($action === 'index' && !Yii::$app->user->can('listClients')) { throw new ForbiddenHttpException(Yii::t('app', 'You are not allowed to list clients')); } // You can also make the check more granular based on the model being accessed if ($action === 'view' && !Yii::$app->user->can('viewClient', ['client_id' => $model->id])) { throw new ForbiddenHttpException(Yii::t('app', 'You are not allowed to view client {client}', ['client' => $model->id])); } } 或未经身份验证的用户,访客@

这有点令人困惑,因为它在?上有所不同,但是您不应该检查用户是否在yii\web\Controller上进行了验证,因为checkAccess()已经执行了检查使用您问题中发布的代码进行过滤,直到authenticator被调用时,您将始终拥有应用程序用户,因此checkAccess()始终匹配,并且@从不匹配。

由于您已注释掉以下行:

?

这意味着CORS飞行前请求将始终失败,并且来宾用户将永远无法登录。任何未通过身份验证的请求将立即产生// $behaviors['authenticator']['except'] = ['OPTIONS', 'login']; 响应。

您似乎正在尝试让所有经过身份验证的用户访问所有操作,而未经身份验证的用户仅访问登录索引 test 操作。如果正确,则无需使用401 unauthorized方法,只需取消注释上面的行并在其中添加操作即可,如下所示:

checkAccess()

未经身份验证的用户将只能访问那些操作。