简体   繁体   中英

Deny access to the application for the role. Yii2

I have 2 applications: frontend and backend.

Users on frontend have role "client".

How do I disable access to the application backend users with "client" role. All other roles are allowed access. site/login on backend allow for all users.

I wrote the following code in my main.php file:

'as beforeRequest' => [
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'allow' => true,
            'controllers' => ['site'],
            'actions' => ['login'],
            'roles' => ['?'],
        ],
        [
            'allow' => false,
            'roles' => ['client'],
        ],
    ],
    'denyCallback' => function () {
        return Yii::$app->response->redirect(['site/login']);
    },
],

I have error: ERR_TOO_MANY_REDIRECTS in chrome.

From the guide 'roles' => ['?'] :

matches a guest user (not authenticated yet)

Since the user is logged in they are stuck in a redirect loop caused by the second rule and the denyCallback ie

  1. User is logged in but is of role client and is therefore not allowed.
  2. Since user has been denied access, redirect to site/login .
  3. See 1.

This can be fixed by omitting the roles element in your first rule:

If [role] is not set or empty, it means this rule applies to all roles.

HOWEVER THIS IS THE WRONG APPROACH

Users who are logged in but are of role client should be denied access to the backend. Sending them to login will not help since they are already logged in. The proper course of action is to send them to the frontend's error page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM