|
| 1 | +--- |
| 2 | +title: Phone Authentication |
| 3 | +sidebar_label: Phone Auth |
| 4 | +--- |
| 5 | + |
| 6 | +Phone authentication allows users to sign in to Firebase using their phone as the authenticator. An SMS message is sent |
| 7 | +to the user (using the provided phone number) containing a unique code. Once the code has been authorized, the user is able to sign |
| 8 | +into Firebase. |
| 9 | + |
| 10 | +> Phone numbers that end users provide for authentication will be sent and stored by Google to improve spam and abuse |
| 11 | +> prevention across Google service, including to, but not limited to Firebase. Developers should ensure they have the |
| 12 | +> appropriate end-user conset prior to using the Firebase Authentication phone number sign-in service.authentication |
| 13 | +
|
| 14 | +Firebase Phone Authentication is not supported in all countries. Please see their [FAQs](https://firebase.google.com/support/faq/#develop) for more information |
| 15 | + |
| 16 | +## Setup |
| 17 | + |
| 18 | +Before starting with Phone Authentication, ensure you have followed these steps: |
| 19 | + |
| 20 | +1. Enable Phone as a Sign-In method in the [Firebase console](https://console.firebase.google.com/u/0/project/_/authentication/providers). |
| 21 | +2. **Android**: If you haven't already set your app's SHA-1 hash in the [Firebase console](https://console.firebase.google.com/), do so. |
| 22 | + See [Authenticating Your Client](https://developers.google.com/android/guides/client-auth) for information about finding your app's SHA-1 hash. |
| 23 | +3. **iOS**: In XCode, [enable push notifications](http://help.apple.com/xcode/mac/current/#/devdfd3d04a1) for your project & ensure |
| 24 | + your APNs authentication key is [configured with Firebase Cloud Messaging (FCM)](https://firebase.google.com/docs/cloud-messaging/ios/certs). |
| 25 | + To view an indepth explaination of this step, view the [Firebase iOS Phone Auth](https://firebase.google.com/docs/auth/ios/phone-auth) documentation. |
| 26 | +4. **Web**: Ensure that you have added your applications domian on the [Firebase console](https://console.firebase.google.com/), under |
| 27 | + **OAuth redirect domains**. |
| 28 | + |
| 29 | +**Note**; Phone number sign-in is only available for use on real devices and the web. To test your authentication flow on device emulators, |
| 30 | +please see [Testing](#testing). |
| 31 | + |
| 32 | +## Usage |
| 33 | + |
| 34 | +FlutterFire provides two individual ways to sign a user in with their phone number. Native (e.g. Android & iOS) platforms provide |
| 35 | +different functionality to validating a phone number than the web, therefore two methods exist for each platform exclusively: |
| 36 | + |
| 37 | +- **Native Platform**: [`verifyPhoneNumber`](!firebase_auth.FirebaseAuth.verifyPhoneNumber). |
| 38 | +- **Web Platform**: [`signInWithPhoneNumber`](!firebase_auth.FirebaseAuth.signInWithPhoneNumber). |
| 39 | + |
| 40 | +### Native: `verifyPhoneNumber` |
| 41 | + |
| 42 | +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 |
| 43 | +[`PhoneAuthCredential`](!firebase_auth_platform_interface.PhoneAuthCredential). |
| 44 | + |
| 45 | +First you must prompt the user for their phone number. Once provided, call the `verifyPhoneNumber()` method: |
| 46 | + |
| 47 | +```dart |
| 48 | +await FirebaseAuth.instance.verifyPhoneNumber( |
| 49 | + phoneNumber: '+44 7123 123 456', |
| 50 | + verificationCompleted: (PhoneAuthCredential credential) {}, |
| 51 | + verificationFailed: (FirebaseAuthException e) {}, |
| 52 | + codeSent: (String verificationId, int resendToken) {}, |
| 53 | + codeAutoRetrievalTimeout: (String verificationId) {}, |
| 54 | +); |
| 55 | +``` |
| 56 | + |
| 57 | +There are 4 seperate callbacks that you must handle, each will determine how you update the application UI: |
| 58 | + |
| 59 | +1. **[verificationCompleted](#verificationCompleted)**: Automatic handling of the SMS code on Android devices. |
| 60 | +2. **[verificationFailed](#verificationFailed)**: Handle failure events such as invalid phone numbers or whethehr the SMS quota has been exceeded. |
| 61 | +3. **[codeSent](#codeSent)**: Handle when a code has been sent to the device from Firebase, used to prompt users to enter the code. |
| 62 | +4. **[codeAutoRetrievalTimeout](#codeAutoRetrievalTimeout)**: Handle a timeout of when automatic SMS code handling fails. |
| 63 | + |
| 64 | +#### verificationCompleted |
| 65 | + |
| 66 | +This handler will only be called on Android devices which support automatic SMS code resolution. |
| 67 | + |
| 68 | +When the SMS code is delivered to the device Android will automatically verify the SMS code without |
| 69 | +requiring the user to manually input the code. If this event occurs, a `PhoneAuthCredential` is automatically provided which can be |
| 70 | +used to sign-in with or link the users phone number. |
| 71 | + |
| 72 | +```dart |
| 73 | +FirebaseAuth auth = FirebaseAuth.instance; |
| 74 | +
|
| 75 | +await auth.verifyPhoneNumber( |
| 76 | + phoneNumber: '+44 7123 123 456', |
| 77 | + verificationCompleted: (PhoneAuthCredential credential) async { |
| 78 | + // ANDROID ONLY! |
| 79 | +
|
| 80 | + // Sign the user in (or link) with the auto-generated credential |
| 81 | + await auth.signInWithCredential(credential); |
| 82 | + }, |
| 83 | +); |
| 84 | +``` |
| 85 | + |
| 86 | +#### verificationFailed |
| 87 | + |
| 88 | +If Firebase returns an error, for example for an incorrect phone number or if the SMS quota for the project has exceeded, |
| 89 | +a `FirebaseAuthException` will be sent to this handler. In this case, you would prompt your user something went wrong depending on the error |
| 90 | +code. |
| 91 | + |
| 92 | +```dart |
| 93 | +FirebaseAuth auth = FirebaseAuth.instance; |
| 94 | +
|
| 95 | +await auth.verifyPhoneNumber( |
| 96 | + phoneNumber: '+44 7123 123 456', |
| 97 | + verificationFailed: (FirebaseAuthException e) { |
| 98 | + if (e.code == 'invalid-phone-number') { |
| 99 | + print('The provided phone number is not valid.'); |
| 100 | + } |
| 101 | +
|
| 102 | + // Handle other errors |
| 103 | + }, |
| 104 | +); |
| 105 | +``` |
| 106 | + |
| 107 | +#### codeSent |
| 108 | + |
| 109 | +When Firebase sends an SMS code to the device, this handler is triggered with a `verificationId` and `resendToken`. |
| 110 | + |
| 111 | +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. |
| 112 | +Once the SMS code has been entered, you can combine the verification ID with the SMS code to create a new `PhoneAuthCredential`: |
| 113 | + |
| 114 | +```dart |
| 115 | +FirebaseAuth auth = FirebaseAuth.instance; |
| 116 | +
|
| 117 | +await auth.verifyPhoneNumber( |
| 118 | + phoneNumber: '+44 7123 123 456', |
| 119 | + codeSent: (String verificationId, int resendToken) async { |
| 120 | + // Update the UI - wait for the user to enter the SMS code |
| 121 | + String smsCode = 'xxxx'; |
| 122 | +
|
| 123 | + // Create a PhoneAuthCredential with the code |
| 124 | + PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(verificationId, smsCode); |
| 125 | +
|
| 126 | + // Sign the user in (or link) with the credential |
| 127 | + await auth.signInWithCredential(phoneAuthCredential); |
| 128 | + }, |
| 129 | +); |
| 130 | +``` |
| 131 | + |
| 132 | +By default, Firebase will not re-send a new SMS message if it has been recently sent. You can however override this behaviour |
| 133 | +by re-calling the `verifyPhoneNumber` method with the resend token to the `forceResendingToken` argument. |
| 134 | +If successful, the SMS message will be resent. |
| 135 | + |
| 136 | +#### codeAutoRetrievalTimeout |
| 137 | + |
| 138 | +On Android devices which support automatic SMS code resolution, this handler will be called if the device has not automatically |
| 139 | +resolved an SMS message within a certain timeframe. Once the timeframe has passed, the device will no longer attempt to resolve |
| 140 | +any incoming messages. |
| 141 | + |
| 142 | +By default, the device waits for 30 seconds however this can be customized with the `timeout` argument: |
| 143 | + |
| 144 | +```dart |
| 145 | +FirebaseAuth auth = FirebaseAuth.instance; |
| 146 | +
|
| 147 | +await auth.verifyPhoneNumber( |
| 148 | + phoneNumber: '+44 7123 123 456', |
| 149 | + timeout: const Duration(seconds: 60), |
| 150 | + codeAutoRetrievalTimeout: (String verificationId) { |
| 151 | + // Auto-resolution timed out... |
| 152 | + }, |
| 153 | +); |
| 154 | +``` |
| 155 | + |
| 156 | +### Web: `signInWithPhoneNumber` |
| 157 | + |
| 158 | +TODO |
| 159 | + |
| 160 | +## Testing |
| 161 | + |
| 162 | +Firebase provides support for locally testing phone numbers: |
| 163 | + |
| 164 | +1. On the Firebase Console, select the "Phone" authentication provider and click on the "Phone numbers for testing" dropdown. |
| 165 | +2. Enter a new phone number (e.g. `+44 7444 555666`) and a test code (e.g. `123456`). |
| 166 | + |
| 167 | +If providing a test phone number to either the `verifyPhoneNumber` or `signInWithPhoneNumber` methods, no SMS will actually be sent. You |
| 168 | +can instead provide the test code directly to the `PhoneAuthProvider` or with `signInWithPhoneNumber`s confirmation result handler. |
0 commit comments