Yii2验证RESTapi的密码

时间:2019-01-28 18:38:05

标签: yii2 firebase-authentication yii2-advanced-app

如果不使用密码,则REST请求通过。否则,您会得到一个错误:

  

错误:

  "name": "Unauthorized",
  "message": "Your request was made with invalid credentials.",
  "code": 0,
  "status": 401,
  "type": "yii\\web\\UnauthorizedHttpException"

以用户模型访问:

   public static function findIdentityByAccessToken($username, $password = null)
    {
        // throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
        //return static::findOne(['username' => $username]);

        $user = static::findOne(['username' => $username]);
        if ($user != null and $user->validatePassword($password)) {
            return $user;
        } else {
            return null;
        }
    }

和validatePassword函数:

   public function validatePassword($password)
    {
        $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
        return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
    }

如何进行身份验证?

1 个答案:

答案 0 :(得分:0)

REST API通常通过使用令牌进行身份验证来工作。有不同类型的身份验证令牌。此示例使用basic auth

控制器

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

然后,您需要在请求中添加一个authorization header,其值为

Basic base64_encode(username:password)