Firebase the Sms Code Has Expired. Please Re-send the Verification Code to Try Again.
How to Setup Firebase
You might need to use Firebase for the following reasons:
- Firebase authentication of users in your app via telephone number.
- Firebase Cloud Messaging (FCM) push notifications (erstwhile GCM).
It might look a bit scary at showtime. But don't panic and let's bank check how to practice this right step by stride.
Firebase business relationship and project registration
Follow these steps to register your Firebase account and create a Firebase projection:
-
Register a Firebase account at Firebase console . You tin can apply your Google account to authenticate at Firebase.
-
Click Add project
Note: If you have a Google project registered for your mobile app, select it from the Project name dropdown menu.
Yous tin can also edit your Project ID if you lot need. A unique ID is assigned automatically to each projection. This ID is used in publicly visible Firebase features. For case, it will be used in database URLs and in your Firebase Hosting subdomain. If yous need to utilise a specific subdomain, you can change it.
-
Fill in the fields required (Project name, Project ID, etc.) and click Continue.
-
Select data sharing for your projection and click Create project. Nosotros have chosen to let but Technical Back up access.
So click Continue.
-
Select platform for which yous need Firebase
-
Make full in the fields on Add Firebase to your Android App screen and click Register App
Connect Firebase SDK
For Android projects Firebase has the following requirements to be added successfully:
- Android OS 4.0 or newer
- Google Play Services 15.0.0 or higher
- The latest version of Android Studio
Hither is a step by step guide how to connect Firebase SDK to your Android Project:
-
Download Google-Services.json config file
-
Open up Project view in Android Studio and upload Google-Services.json file y'all take simply downloaded into the root directory of your Android app module.
-
Add together Firebase SDK according to the instructions in your Firebase console
-
Add Google services plugin to your project build.gradle file
-
Add together Google services plugin in the lesser of your module build.gradle file.
-
Click Sync Now at the pop-up in your Android Studio
You are washed now.
Firebase authentication
This choice allows users in your app cosign themselves via phone number. If yous use this method for user authentication, the user receives an SMS with verification code and authenticates via that code in your app.
You need to follow these steps to add Firebase authentication to your Android projection:
-
Add Firebase hallmark dependency to your Module build.gradle file:
-
Sync your project as prompted by Android Studio:
-
Detect your app'southward SHA-ane hash - check Authenticating Your Client guide.
-
Add your app's SHA-i hash in your Firebase console >> Project settings tab:
And then:
-
Go to Firebase console >> Authentication >> Sign-in method section:
-
Enable Phone number sign-in method:
-
Add
PhoneAuthProvider.verifyPhoneNumber
method to request that Firebase verify the user's phone number:
PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks
PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Telephone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback bounden) mCallbacks) // OnVerificationStateChangedCallbacks
Annotation: verifyPhoneNumber
method is reentrant: if yous phone call it multiple times, such equally in an activeness'due south onStart
method, verifyPhoneNumber
method volition not send a second SMS unless the original request has timed out.
Important note: As a best do please do not forget to inform your users that if they use phone sign-in, they might receive an SMS message for verification and standard rates utilise.
-
(Optional) To resume the phone number sign in process if your app closes before the user can sign in (if the user checks SMS app, for example), after
verifyPhoneNumber
method is chosen, set a flag that indicates verification is in progress. Then, save the flag in your Activity'sonSaveInstanceState
method and restore the flag inonRestoreInstanceState
. In your Activity'sonStart
method, check if verification is already in progress, and if it is not, telephone callverifyPhoneNumber
again. Exist sure to articulate the flag when verification completes or fails. Check this guide for more than details. -
setLanguageCode
method on your Auth example allows specifying the auth language and therefore localize SMS message sent by Firebase:
auth.setLanguageCode("fr"); // To apply the default app language instead of explicitly setting it. // auth.useAppLanguage();
auth.setLanguageCode("fr") // To employ the default app linguistic communication instead of explicitly setting it. // auth.useAppLanguage();
- When y'all call
PhoneAuthProvider.verifyPhoneNumber
method, you must too provide an case ofOnVerificationStateChangedCallbacks
, which contains implementations of the callback functions that handle the results of the request:
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // This callback will be invoked in two situations: // 1 - Instant verification. In some cases the phone number can be instantly // verified without needing to transport or enter a verification lawmaking. // two - Auto-retrieval. On some devices Google Play services can automatically // detect the incoming verification SMS and perform verification without // user action. Log.d(TAG, "onVerificationCompleted:" + credential); signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in an invalid asking for verification is made, // for instance if the the phone number format is not valid. Log.w(TAG, "onVerificationFailed", e); if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (east instanceof FirebaseTooManyRequestsException) { // The SMS quota for the projection has been exceeded // ... } // Show a message and update the UI // ... } @Override public void onCodeSent(Cord verificationId, PhoneAuthProvider.ForceResendingToken token) { // The SMS verification code has been sent to the provided phone number, we // at present need to ask the user to enter the lawmaking and then construct a credential // by combining the lawmaking with a verification ID. Log.d(TAG, "onCodeSent:" + verificationId); // Salve verification ID and resending token so we can use them later mVerificationId = verificationId; mResendToken = token; // ... } };
mCallbacks = object : OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) { // This callback will be invoked in two situations: // i - Instant verification. In some cases the telephone number can exist instantly // verified without needing to ship or enter a verification code. // 2 - Auto-retrieval. On some devices Google Play services tin can automatically // detect the incoming verification SMS and perform verification without // user action. Log.d(TAG, "onVerificationCompleted:$credential") signInWithPhoneAuthCredential(credential) } override fun onVerificationFailed(east: FirebaseException) { // This callback is invoked in an invalid request for verification is made, // for case if the the phone number format is non valid. Log.w(TAG, "onVerificationFailed", e) if (due east is FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (due east is FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Prove a message and update the UI // ... } override fun onCodeSent(verificationId: String, token: ForceResendingToken ) { // The SMS verification code has been sent to the provided phone number, nosotros // at present need to ask the user to enter the code and so construct a credential // by combining the code with a verification ID. Log.d(TAG, "onCodeSent:$verificationId") // Salvage verification ID and resending token so we tin use them after mVerificationId = verificationId mResendToken = token // ... } }
- Create a
PhoneAuthCredential
object using the verification code and the verification ID that was passed toonCodeSent
callback. You become aPhoneAuthCredential
object whenonVerificationCompleted
is chosen. To createPhoneAuthCredential
object, callPhoneAuthProvider.getCredential
:
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
val credential = PhoneAuthProvider.getCredential(verificationId, code)
- Consummate the sign-in menstruation past passing the
PhoneAuthCredential
object toFirebaseAuth.signInWithCredential
:
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener <AuthResult > () { @Override public void onComplete(@NonNull Task <AuthResult > chore) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = chore.getResult().getUser(); // ... } else { // Sign in failed, brandish a message and update the UI Log.w(TAG, "signInWithCredential:failure", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid } } } }); }
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (chore.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") val user = chore.result?.user // ... } else { // Sign in failed, display a message and update the UI Log.w(TAG, "signInWithCredential:failure", chore.exception) if (chore.exception is FirebaseAuthInvalidCredentialsException) { // The verification lawmaking entered was invalid } } } }
- Get Firebase
access_token
after SMS lawmaking verification as follows:
public Task <GetTokenResult > getIdToken (boolean forceRefresh)
fun getIdToken(forceRefresh: Boolean): Job <GetTokenResult >
Example of the method implementation:
FirebaseAuth.getInstance().getCurrentUser().getIdToken(forceRefresh);
FirebaseAuth.getInstance().currentUser?.getIdToken(forceRefresh)
-
Add ConnectyCube user sign in to your projection equally follows:
i) Become your Projection ID from your Firebase console:
two) Pass your Firebase
project_id
and Firebaseaccess_token
parameters tosignInUsingFirebase
method:
Cord projectId = "..."; String accessToken = "..."; ConnectycubeUsers.signInUsingFirebase(projectId, accessToken).performAsync(new EntityCallback <ConnectycubeUser > () { @Override public void onSuccess(ConnectycubeUser user, Bundle args) { } @Override public void onError(ResponseException mistake) { } });
val projectId = "..." val accessToken = "..." ConnectycubeUsers.signInUsingFirebase(projectId, accessToken) .performAsync(object : EntityCallback <ConnectycubeUser > { override fun onSuccess(user: ConnectycubeUser, args: Packet?) { } override fun onError(error: ResponseException) { } })
-
Endeavor running a examination. In one case your user is logged in successfully, you volition find him/her in your Dashboard >> Your App >> Users department.
So now you know how to employ Firebase features in your ConnectyCube apps. If yous take any difficulties - please let u.s. know via support aqueduct
Source: https://developers.connectycube.com/android/firebase-setup-guide
0 Response to "Firebase the Sms Code Has Expired. Please Re-send the Verification Code to Try Again."
Post a Comment