Search code examples
phpyii2basic-authenticationbehavior

Yii2 behavior in controller don't work


I have properly working controller and I want to attach there a behavior of basic auth. I add method behaviors() to controller and var_dump($this->behaviors); in before action. Everything is correct. Problem is that HttpBasicAuth doesnt work with method.

Here's my code:

public function behaviors()
{
    return [
        'basicAuth' => [
            'class' => \yii\filters\auth\HttpBasicAuth::className(),
            'auth' => function ($username, $password) {
                if (! $this->isValidUser($username, $password)) {
                    return User::findByUsername($username);
                }

                return false;
            }
        ],

    ];
}

Solution

  • guys, I solved this bug.

    If we want to call behaviors and we have beforeAction metohd in our controller. Your beforeAction should look like. Method which calls behaviors located in method beforeAction of parent class.

    public function beforeAction($event)
    {
        ...
    
        return parent::beforeAction($event);
    }