Yii2 为 REST api 验证密码

Yii2 validate password in for RESTapi

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

Error:

  "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;
        }
    }

和验证密码功能:

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

如何认证?

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

控制器

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

然后您需要将 authorization header 添加到您的请求中,其值为

Basic base64_encode(username:password)