PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

[FIXED] yii2 I want to allow only index action

 December 30, 2021     yii, yii2-advanced-app, yii2-basic-app     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing