LostDok
LostDok

Reputation: 155

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.phpfile:

'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.

Upvotes: 0

Views: 1189

Answers (1)

topher
topher

Reputation: 14860

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 i.e.

  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.

Upvotes: 1

Related Questions