Firebase Phone Authentication Error: The SMS Code Has Expired

Viewed 11609

Having implemented the FireBase phone authentication as per the documentation, I get several problems.

  1. some numbers cannot be authenticated: I am using Airtel as my service provider.

On the log, I can confirm that the code has been sent but I haven't received it on my phone:

D/PhoneAuthenticating: onCodeSent:AM5PThBss5tbYdpNW5R9Q7o8zOYeHvd7lnZ1KBlS...

  1. Switching to another carrier, I can receive the code but then it says the SMS code has expired immediately after trying to verify. I make more attempts and result is the same

W/PhoneAuthenticating: signInWithCredential:failure com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The sms code has expired. Please re-send the verification code to try again. at com.google.android.gms.internal.nf.zzK(Unknown Source) at com.google.android.gms.internal.mg.zza(Unknown Source) at com.google.android.gms.internal.oa.zzL(Unknown Source) at com.google.android.gms.internal.oc.onFailure(Unknown Source) at com.google.android.gms.internal.nj.onTransact(Unknown Source) at android.os.Binder.execTransact(Binder.java:446)

This exception is thrown:

FirebaseAuthInvalidCredentialsException

code expiry takes more in than 3599 seconds in firebase. The time taken to verify is less than a minute

3 Answers

Just so that you know there's an auto retrieval section in firebase phone authentication which will read sms and invalidate it in the background. The callback for that auto-retrieval should be used to authenticate your user without him entering the sms manually.

While setting the PhoneVerificationCompleted handler, you need to the following,

  1. Comment the line,

    //_firebaseAuth.signInWithCredential(phoneAuthCredential);

  2. Replace AuthCredential with PhoneAuthCredential,

    PhoneVerificationCompleted verificationCompleted = (PhoneAuthCredential phoneAuthCredential)

  3. Add async to this method,

    PhoneVerificationCompleted verificationCompleted = (PhoneAuthCredential phoneAuthCredential) async

It should work fine!

Finally got the solution. During authenticating the user, we use the same method for sending the code only that we add a new parameter.

    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    FirebaseAuth.getInstance().signInWithCredential(credential)
    Toast.makeText(this, "Verifying...", Toast.LENGTH_SHORT).show();
Related