As beforeRequest leading to infinite recursion

I’m trying to follow this advice about setting all controllers to require login, so my config\web.php $config definition includes

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

But when I run it, Firefox says “The page isn’t redirecting properly”.

In the Yii Server command window, I can see what’s happening. The first few lines look like this:

[Sat Nov 16 09:17:53 2019] ::1:51836 [302]: /

[Sat Nov 16 09:17:53 2019] ::1:51837 [302]: /[site/login]

[Sat Nov 16 09:17:53 2019] ::1:51840 [302]: /[site/[site/login]

[Sat Nov 16 09:17:53 2019] ::1:51841 [302]: /[site/[site/[site/login]

[Sat Nov 16 09:17:53 2019] ::1:51842 [302]: /[site/[site/[site/[site/login]

This goes on for 20 times until the browser apparently puts a stop to it.

I think what must be happening is that the deny callback calls the site controller, which causes the beforeRequest to be executed again, which calls the deny callback again, and so on, “infinitely”. But I don’t know what I did wrong and how to stop it. I removed all the access behavior lines from the site controller; perhaps I need to put something back in there to stop it?

Never mind. Someone pointed out on StackOverflow that I have my quotes wrong in the redirect statement, and that was the entire problem. I’d delete this question except I don’t see a way to do that.

'denyCallback' => function() {
    return Yii::$app->response->redirect('[/site/login]');
},

[/site/login], not [site/login]

1 Like