Thursday, December 30, 2021

[FIXED] yii2 I want to allow only index action

Issue

I have tried to allow only index action by using this behaviors() function right now it's denied index also

Can anyone solve and explain the rules return.

<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\filters\AccessControl;

/**
 * Doctor Controller API
 */
class DoctorController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\Doctor';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'only' => ['index'],
                'rules' => [
                    [
                        'allow' => false,
                        'verbs' => ['POST']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['index'],
                        'verbs' => ['GET'],
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    // everything else is denied
                ],
            ],
        ];
    }
}

Solution

I figured it out after reading the documents

by overwriting the original access behaviors it will decide anything not mentioned as allowed.

so, you will need only one rule of allowing an action without mantioing verbs nor roles, but you may if you want to restrict it more.

<?php

namespace api\modules\v1\controllers;

use Yii;
use api\modules\v1\models\Doctor;
use yii\rest\ActiveController;

/**
 * Doctor Controller API
 */
class DoctorController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\Doctor';

    public function behaviors()
    {

        $behaviors = parent::behaviors();

        $behaviors['access'] = [
            'class' => \yii\filters\AccessControl::className(),
            'rules' => [
                [
                    // All actions
                    'allow' => true,
                    'actions' => ['index'],
                ],
            ],
        ];

        return $behaviors;
    }

}


Answered By - Mansour Alnasser

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.