简体   繁体   中英

Firebase auth with mobile code (phone auth) sign in with code expired

Firebase phone auth when correctly implemented gives the developer a verification code which must be typed to confirm the mobile phone.

When you check the verificationID that Firebase provides plus the verification code, you get verified and consequently logged in.

Using this method, a user can confirm the code and login:

let credential = PhoneAuthProvider.provider().credential(
    withVerificationID: verificationID,
    verificationCode: verificationCode)*

PhoneAuthProvider.provider().verifyPhoneNumber(self.phoneNum.text!, uiDelegate: nil) { (verificationID, error) in
    UserDefaults.standard.set(verificationID, forKey: "authVID")
}        

Now, you need the verification code sent to login.

I get the verificationID and save it to UserDefaults .

But after that, when the code expires I can't proceed with the login because it asks me again for another verification code.

How can I make a login using only the verificationID generated by firebase?

I tried the method:

Auth.auth().signIn(withCustomToken: UserDefaults.standard.string(forKey: "authVID") ?? "")

but firebase says that the authentication token is invalid.

I don't know which method I can use to make the login using only the token provided by firebase.

First you need to call the method to verify mobile number. Once mobile number verified you will get OTP on verified mobile number. So write following method to verify mobile number.

PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
  if let error = error {
     // Show alert here
     return
  }
  // Sign in using the verificationID and the code sent to the user
  // Here your can store your verificationID in user default and later used for sign in. Or pass this verification id to your next view controller for OTP verification.
    UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
}

Next in OTP verification screen when user enter OTP you can create following credentials to sign in.

verificationId - we have stored in UserDefault verificationCode - OTP which are available though mobile message.

// Get verification Id from User Default
let verificationID = UserDefaults.standard.string(forKey: "authVerificationID")

let credential = PhoneAuthProvider.provider().credential(
    withVerificationID: verificationID,
    verificationCode: verificationCode)

Now call signing method.

Auth.auth().signIn(with: credential) { (user, error) in
  if let error = error {
    // ...
    return
  }
  // User is signed in
  // Here sign in completed.
  }
}

Here Sign in completed, now you can navigate to screen which will open after successfully login.

To set home screen when application re-open and your want to set directly home screen write following code.

func setInitialViewController() {
    if Auth.auth().currentUser != nil {
        // setup home screen
    } else {
        //Setup login screen
    }
}

And call the above method from AppDelegate's didFinishLaunchingWithOptions method.

I hope this will help you.

Actually, that exactly what I did. The problem is, after some minutes or day, when I try to sign in using this same method:

Auth.auth().signIn(with: credential) { (user, error) in

Firebase returns telling that the code used inside the credential has expired:

Error Domain=FIRAuthErrorDomain Code=17051 "The SMS code has expired. Please re-send the verification code to try again." UserInfo={NSLocalizedDescription=The SMS code has expired. Please re-send the verification code to try again., error_name=ERROR_SESSION_EXPIRED}

Phone Authentication and get OTP for given mobile number and verify that OTP

Auth.auth().settings!.isAppVerificationDisabledForTesting = false
        PhoneAuthProvider.provider().verifyPhoneNumber(textfieldPhoneNumber.text!,uiDelegate: nil) { (verificationID, error) in
            if error != nil {
                return
            }
            let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID ?? "",verificationCode: self.verificationcode)
            Auth.auth().signInAndRetrieveData(with: credential) { (authData, error) in
                if ((error) != nil) {
                    return
                }
                if let user  = authData!.user as? User {
                    authData!.user.getIDToken(completion: { user, error in })
                    if error != nil {
                        return
                    }
                    let uid = user.uid
                    let RefereshToken = user.refreshToken
                    let token = user.phoneNumber
                    print(uid)
                    print(RefereshToken as Any)
                    print(token as Any)
                }

                print(User.self as Any)

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM