Yii2: Yii2 Rest checkAccess ViewAction

Created on 9 Mar 2016  路  5Comments  路  Source: yiisoft/yii2

I don't quite understand the logic of checkAccess in the Yii Rest API

yii2\rest\ViewAction.php

$model = $this->findModel($id);
if ($this->checkAccess) {
    call_user_func($this->checkAccess, $this->id, $model);
}

Why would I query the model before I have verified access?

Also the model is irrelevant to whether I have access to it not.

question

Most helpful comment

checkAccess is more about authorization. Authentication should be already handled before getting there. Here is one more example:

Your model represents an Article and only its Author is allowed to Edit or Delete it:

public function checkAccess($action, $model = null, $params = [])
{
    if ($action === 'update' or $action === 'delete') {
        if ($model->author_id !== \Yii::$app->user->id)
            throw new \yii\web\ForbiddenHttpException('You can only '.$action.' articles that you\'ve created.');
    }
}

All 5 comments

this can be record-level access, not just access of controller/action

I'll give you an example:
I have a model called Widgets and I have valid access to the action, and I want to access widget id 5

Rest Call:
Authorization: Bearer ABCDE
GET widget/id/5

I have another model widget_permissions that has a record
ABCDE -> [1,2,3,4,6]
which shows ABCDE does not have access to widget 5 but I still query it regardless?

checkAccess is more about authorization. Authentication should be already handled before getting there. Here is one more example:

Your model represents an Article and only its Author is allowed to Edit or Delete it:

public function checkAccess($action, $model = null, $params = [])
{
    if ($action === 'update' or $action === 'delete') {
        if ($model->author_id !== \Yii::$app->user->id)
            throw new \yii\web\ForbiddenHttpException('You can only '.$action.' articles that you\'ve created.');
    }
}

_This is an automated comment, triggered by adding the label question._

Please note, that the GitHub Issue Tracker is for bug reports and feature requests only.

We are happy to help you on the support forum, on IRC (#yii on freenode), or Gitter.

Please use one of the above mentioned resources to discuss the problem.
If the result of the discussion turns out that there really is a bug in the framework, feel free to
come back and provide information on how to reproduce the issue. This issue will be closed for now.

Was this page helpful?
0 / 5 - 0 ratings