如何使用Firebase在Flutter中进行电话身份验证?

Moh*_*548 5 firebase flutter

我搜索了许多网站,但没有找到使用Firebase在Flutter中实现电话身份验证的方法。谁能告诉我该怎么做?

Moh*_*548 27

有据可查的工作演示项目在这里

下面是详细流程

脚步

  1. 询问用户的电话号码
  2. 从 Firebase 获取 OTP
  3. 登录 Firebase

规则

  • 登录/登录以相同的方式完成。
  • OTP 仅用于获取AuthCrendential对象
  • AuthCredentialobject 是唯一用于登录用户的东西。它是从verificationCompleted回调函数中verifyPhoneNumber或从PhoneAuthProvider.

(不要担心它是否令人困惑,继续阅读,你会明白的)

工作流程

  1. 用户给出 phoneNumber
  2. Firebase 发送 OTP
  3. 登录用户
    • 如果带有 的 SIM 卡phoneNumber不在当前运行该应用程序的设备中,
      • 我们必须先询问OTP并获得AuthCredential对象
      • 接下来我们可以使用它AuthCredential来登录这个方法即使phoneNumber在设备中也有效
    • 否则,如果用户提供的 SIM 电话号码在运行应用程序的设备中,
      • 我们可以在没有 OTP 的情况下登录。
      • 因为函数的verificationCompleted回调submitPhoneNumber提供了AuthCredential登录用户所需的对象
      • 但在前一种情况下,它不会被调用,因为 SIM 不在手机中。

职能

  • 提交电话号码
Future<void> _submitPhoneNumber() async {
    /// NOTE: Either append your phone number country code or add in the code itself
    /// Since I'm in India we use "+91 " as prefix `phoneNumber`
    String phoneNumber = "+91 " + _phoneNumberController.text.toString().trim();
    print(phoneNumber);

    /// The below functions are the callbacks, separated so as to make code more readable
    void verificationCompleted(AuthCredential phoneAuthCredential) {
      print('verificationCompleted');
      ...
      this._phoneAuthCredential = phoneAuthCredential;
      print(phoneAuthCredential);
    }

    void verificationFailed(AuthException error) {
      ...
      print(error);
    }

    void codeSent(String verificationId, [int code]) {
      ...
      print('codeSent');
    }

    void codeAutoRetrievalTimeout(String verificationId) {
      ...
      print('codeAutoRetrievalTimeout');
    }

    await FirebaseAuth.instance.verifyPhoneNumber(
      /// Make sure to prefix with your country code
      phoneNumber: phoneNumber,

      /// `seconds` didn't work. The underlying implementation code only reads in `milliseconds`
      timeout: Duration(milliseconds: 10000),

      /// If the SIM (with phoneNumber) is in the current device this function is called.
      /// This function gives `AuthCredential`. Moreover `login` function can be called from this callback
      verificationCompleted: verificationCompleted,

      /// Called when the verification is failed
      verificationFailed: verificationFailed,

      /// This is called after the OTP is sent. Gives a `verificationId` and `code`
      codeSent: codeSent,

      /// After automatic code retrival `tmeout` this function is called
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
    ); // All the callbacks are above
  }
Run Code Online (Sandbox Code Playgroud)
  • 提交OTP
void _submitOTP() {
    /// get the `smsCode` from the user
    String smsCode = _otpController.text.toString().trim();

    /// when used different phoneNumber other than the current (running) device
    /// we need to use OTP to get `phoneAuthCredential` which is inturn used to signIn/login
    this._phoneAuthCredential = PhoneAuthProvider.getCredential(
        verificationId: this._verificationId, smsCode: smsCode);

    _login();
  }
Run Code Online (Sandbox Code Playgroud)
  • 登录/登录
Future<void> _login() async {
    /// This method is used to login the user
    /// `AuthCredential`(`_phoneAuthCredential`) is needed for the signIn method
    /// After the signIn method from `AuthResult` we can get `FirebaserUser`(`_firebaseUser`)
    try {
      await FirebaseAuth.instance
          .signInWithCredential(this._phoneAuthCredential)
          .then((AuthResult authRes) {
        _firebaseUser = authRes.user;
        print(_firebaseUser.toString());
      });
      ...
    } catch (e) {
      ...
      print(e.toString());
    }
  }
Run Code Online (Sandbox Code Playgroud)
  • 登出
  Future<void> _logout() async {
    /// Method to Logout the `FirebaseUser` (`_firebaseUser`)
    try {
      // signout code
      await FirebaseAuth.instance.signOut();
      _firebaseUser = null;
      ...
    } catch (e) {
      ...
      print(e.toString());
    }
  }
Run Code Online (Sandbox Code Playgroud)

有关实施的更多详细信息,请参阅此处lib/main.dart文件。

如果您发现问题,欢迎对此答案和此repo README 进行编辑


Kar*_*gla 6

当前_signInPhoneNumber已弃用,因此请使用以下命令:

try {
    AuthCredentialauthCredential = PhoneAuthProvider.getCredential(verificationId: verificationId, verificationsCode: smsCode);

    await _firebaseAuth
      .signInWithCredential(authCredential)
      .then((FirebaseUser user) async {
         final FirebaseUser currentUser = await _firebaseAuth.currentUser();
         assert(user.uid == currentUser.uid);
         print('signed in with phone number successful: user -> $user');
    }
}
Run Code Online (Sandbox Code Playgroud)