How do I define Access control not working in YII 2

167 Views Asked by At

I have define access control as below in my controller but it always redirect to Login page. Why does this happen?

             'access' => [
                'class' => AccessControl::className(),
                'only' => ['makepayment'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['makepayment'],
                        'roles' => ['?'],
                    ],
                ],
            ],
2

There are 2 best solutions below

2
Raahul Shrivastava On

Access control in Yii 2 is typically defined using the RBAC (Role-Based Access Control) system. To determine if access control is not working as expected, you can follow these steps:

  1. Check the RBAC configuration file: Make sure that the RBAC configuration file is properly configured and that it contains the correct roles, permissions, and rules.

  2. Check the controller/action permissions: Make sure that the controller/action that you are trying to access has the correct permission defined in the RBAC configuration file. You can check this by calling the Yii::$app->user->can('permissionName') method in your controller action and ensuring that it returns true.

  3. Check the user's role and permissions: Make sure that the user has been assigned the correct role and has the necessary permissions to access the controller/action. You can check this by calling the Yii::$app->authManager->getRolesByUser($userId) and Yii::$app->authManager->getPermissionsByUser($userId) methods and verifying that the user has the necessary roles and permissions.

  4. Check the RBAC hierarchy: Make sure that the RBAC hierarchy is properly configured and that it allows the user to access the necessary permissions. You can check this by calling the Yii::$app->authManager->getPermission($permissionName)->getRuleName() method and verifying that the corresponding rule is properly defined.

If none of these steps resolve the issue, you may need to enable logging and debugging to determine the root cause of the access control problem. This can be done by setting the Yii::$app->log->targets and Yii::$app->errorHandler->errorAction properties in your configuration file.

0
Hashan On
     'as beforeRequest' => [
        'class' => 'yii\filters\AccessControl',
        'rules' => [
            [
                'actions' => ['login', 'error', 'makepayment', 'returnpayment'],
                'allow' => true,
            ],
            [

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

In config->web.php file Ihad to define them again. It worked fine. Thanks all.