Yii2 Rest API基本身份验证

时间:2019-01-28 13:27:08

标签: rest yii2 basic-authentication yii2-advanced-app

我需要Yii2 rest API中的基本身份验证:

Api控制器:

public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator']['class'] = HttpBasicAuth::className();
        $behaviors['authenticator']['auth'] = function ($username, $password) {
            return \app\models\User::findOne([
                'username' => $username,
                'password' => $password,
            ]);
        };
    }

我的Requwest:

  

login:password @ api / users

如何解决?

错误:

  

为foreach()提供的参数无效

 if ($this->_behaviors === null) {
            $this->_behaviors = [];
            foreach ($this->behaviors() as $name => $behavior) {
                $this->attachBehaviorInternal($name, $behavior);
            }
        }

与“ foreach”对齐。

1 个答案:

答案 0 :(得分:0)

在控制器中:

   public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
        ];
        return $behaviors;
    }

获取网址:用户名:password @ api / users