yii2yii2-user

Controller / Action for guest users (Does not require authentication) using Yii2-user


I am using Yii2 (basic) and Yii2-user for a website with users. For most actions it's necessary to be authenticated. How could I make a controller / action accessible as a guest?

I have tried things like this in the guest's controller:

'rules' => [
    [
        'allow' => true,
        'actions' => ['index', 'confirm', 'download-form', 'upload-form'],
    ]
],

And this should be enough. But nope. I suspect that it is Yii2-user module who gets in the way and always redirects me to login.

And I have added the module in the web.php configuration like this:

'components' => [
    ...
    ...

    'user' => [
        'class' => 'nkostadinov\user\components\User',
        'identityClass' => 'nkostadinov\user\models\User',
        'enableConfirmation' => false,
        'as firstLoginPolicy' => [ 
            'class' => 'nkostadinov\user\behaviors\FirstLoginPolicyBehavior'
        ],
    ],
],

Any idea?


Solution

  • I have solved it as follows.

    In my web.php configuration I had this:

    'modules' => [
    ...
    ],
    'as access' => [
        'class' => \yii\filters\AccessControl::className(),//AccessControl::className(),
        'rules' => [
            [
                'actions' => ['login', 'error', 'request', 'change-password'],
                'allow' => true,
                'roles' => ['?']
            ],
            [
                //'actions' => ['logout', 'index'], // add all actions to take guest to login page
                'allow' => true,
                'roles' => ['@'],
            ],        
       ],
    ],
    'params' => [ ... ]
    

    So, I have added this new rule to grant guest users access to all actions of this controller:

    [
        'controllers' => ['mymodule/my-controller'],    
        'allow' => true,    
    ],
    

    And that's it.