micky
micky

Reputation: 317

Using access control in yii2

I am using access control to allow the access to only authenticated users.

public function behaviors()
        {
            return [
                'access' => [
                'class' => AccessControl::className(),
                'only' => ['display'],
                'rules' => [
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {

                         return $this->redirect(Yii::$app->request->baseUrl.'/site/login');      
                        }],

                    ],
                ],
            ];
        }

        public function actionDisplay()
        {
                echo "display";
        } 

When i try to access the display action while not logging in i am redirected to login page. But when i try to access the display action even with logged in it is redirecting to index page. what am i doing wrong?

Upvotes: 2

Views: 446

Answers (2)

micky
micky

Reputation: 317

Nothing was wrong with the code. just 'matchCallback' which is called to the authenticated user and redirected to login which eventually redirects to index if logged in. Removing the 'matchCallback' solved it.

'rules' => [
             [
              'allow' => true,
              'roles' => ['@'],
              ],
           ],

Upvotes: 1

Hikmat
Hikmat

Reputation: 460

add 'actions' => [ 'display'],

like below

'rules' => [
                // allow authenticated users
                [
                    'actions' => [ 'display'],
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function ($rule, $action) {

                     return $this->redirect(Yii::$app->request->baseUrl.'/site/login');      
                    }],

                ],

normally it work for me

Upvotes: 1

Related Questions