title | sidebar_label |
---|---|
Phone Authentication |
Phone Auth |
Phone authentication allows users to sign in to Firebase using their phone as the authenticator. An SMS message is sent to the user (using the provided phone number) containing a unique code. Once the code has been authorized, the user is able to sign into Firebase.
Phone numbers that end users provide for authentication will be sent and stored by Google to improve spam and abuse prevention across Google service, including to, but not limited to Firebase. Developers should ensure they have the appropriate end-user conset prior to using the Firebase Authentication phone number sign-in service.authentication
Firebase Phone Authentication is not supported in all countries. Please see their FAQs for more information
Before starting with Phone Authentication, ensure you have followed these steps:
- Enable Phone as a Sign-In method in the Firebase console.
- Android: If you haven't already set your app's SHA-1 hash in the Firebase console, do so. See Authenticating Your Client for information about finding your app's SHA-1 hash.
- iOS: In XCode, enable push notifications for your project & ensure your APNs authentication key is configured with Firebase Cloud Messaging (FCM). To view an indepth explaination of this step, view the Firebase iOS Phone Auth documentation.
- Web: Ensure that you have added your applications domian on the Firebase console, under OAuth redirect domains.
Note; Phone number sign-in is only available for use on real devices and the web. To test your authentication flow on device emulators, please see Testing.
FlutterFire provides two individual ways to sign a user in with their phone number. Native (e.g. Android & iOS) platforms provide different functionality to validating a phone number than the web, therefore two methods exist for each platform exclusively:
- Native Platform:
verifyPhoneNumber
. - Web Platform:
signInWithPhoneNumber
.
On native platforms, the users phone number must be first verified and then the user can either sign-in or link their account with a
PhoneAuthCredential
.
First you must prompt the user for their phone number. Once provided, call the verifyPhoneNumber()
method:
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
verificationCompleted: (PhoneAuthCredential credential) {},
verificationFailed: (FirebaseAuthException e) {},
codeSent: (String verificationId, int resendToken) {},
codeAutoRetrievalTimeout: (String verificationId) {},
);
There are 4 seperate callbacks that you must handle, each will determine how you update the application UI:
- verificationCompleted: Automatic handling of the SMS code on Android devices.
- verificationFailed: Handle failure events such as invalid phone numbers or whethehr the SMS quota has been exceeded.
- codeSent: Handle when a code has been sent to the device from Firebase, used to prompt users to enter the code.
- codeAutoRetrievalTimeout: Handle a timeout of when automatic SMS code handling fails.
This handler will only be called on Android devices which support automatic SMS code resolution.
When the SMS code is delivered to the device Android will automatically verify the SMS code without
requiring the user to manually input the code. If this event occurs, a PhoneAuthCredential
is automatically provided which can be
used to sign-in with or link the users phone number.
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
verificationCompleted: (PhoneAuthCredential credential) async {
// ANDROID ONLY!
// Sign the user in (or link) with the auto-generated credential
await auth.signInWithCredential(credential);
},
);
If Firebase returns an error, for example for an incorrect phone number or if the SMS quota for the project has exceeded,
a FirebaseAuthException
will be sent to this handler. In this case, you would prompt your user something went wrong depending on the error
code.
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
verificationFailed: (FirebaseAuthException e) {
if (e.code == 'invalid-phone-number') {
print('The provided phone number is not valid.');
}
// Handle other errors
},
);
When Firebase sends an SMS code to the device, this handler is triggered with a verificationId
and resendToken
.
Once triggered, it would be a good time to update your application UI to prompt the user to enter the SMS code they're expecting.
Once the SMS code has been entered, you can combine the verification ID with the SMS code to create a new PhoneAuthCredential
:
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
codeSent: (String verificationId, int resendToken) async {
// Update the UI - wait for the user to enter the SMS code
String smsCode = 'xxxx';
// Create a PhoneAuthCredential with the code
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(verificationId, smsCode);
// Sign the user in (or link) with the credential
await auth.signInWithCredential(phoneAuthCredential);
},
);
By default, Firebase will not re-send a new SMS message if it has been recently sent. You can however override this behaviour
by re-calling the verifyPhoneNumber
method with the resend token to the forceResendingToken
argument.
If successful, the SMS message will be resent.
On Android devices which support automatic SMS code resolution, this handler will be called if the device has not automatically resolved an SMS message within a certain timeframe. Once the timeframe has passed, the device will no longer attempt to resolve any incoming messages.
By default, the device waits for 30 seconds however this can be customized with the timeout
argument:
FirebaseAuth auth = FirebaseAuth.instance;
await auth.verifyPhoneNumber(
phoneNumber: '+44 7123 123 456',
timeout: const Duration(seconds: 60),
codeAutoRetrievalTimeout: (String verificationId) {
// Auto-resolution timed out...
},
);
TODO
Firebase provides support for locally testing phone numbers:
- On the Firebase Console, select the "Phone" authentication provider and click on the "Phone numbers for testing" dropdown.
- Enter a new phone number (e.g.
+44 7444 555666
) and a test code (e.g.123456
).
If providing a test phone number to either the verifyPhoneNumber
or signInWithPhoneNumber
methods, no SMS will actually be sent. You
can instead provide the test code directly to the PhoneAuthProvider
or with signInWithPhoneNumber
s confirmation result handler.