You can use Firebase Authentication to sign in a user by sending an SMS message to the user's phone. The user signs in using a one-time code contained in the SMS message.
The easiest way to add phone number sign-in to your app is to use FirebaseUI, which includes a drop-in sign-in widget that implements sign-in flows for phone number sign-in, as well as password-based and federated sign-in. This document describes how to implement a phone number sign-in flow using the Firebase SDK.
Before you begin
- Add Firebase to your iOS project.
- Include the following pods in your
Podfile:pod 'Firebase/Auth'
- If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
Also, note that phone number sign-in requires a physical device and won't work on a simulator.
Security concerns
Authentication using only a phone number, while convenient, is less secure than the other available methods, because possession of a phone number can be easily transferred between users. Also, on devices with multiple user profiles, any user that can receive SMS messages can sign in to an account using the device's phone number.
If you use phone number based sign-in in your app, you should offer it alongside more secure sign-in methods, and inform users of the security tradeoffs of using phone number sign-in.
Enable Phone Number sign-in for your Firebase project
To sign in users by SMS, you must first enable the Phone Number sign-in method for your Firebase project:
- In the Firebase console, open the Authentication section.
- On the Sign-in Method page, enable the Phone Number sign-in method.
Firebase's phone number sign-in request quota is high enough that most apps won't be affected. However, if you need to sign in a very high volume of users with phone authentication, you might need to upgrade your pricing plan. See the pricing page.
Start receiving APNs notifications
To use phone number authentication, your app must be able to receive APNs notifications from Firebase. When you sign in a user with their phone number for the first time on a device, Firebase Authentication sends a silent push notification to the device to verify that the phone number sign-in request comes from your app. (For this reason, phone number sign-in cannot be used on a simulator.)
To enable APNs notifications for use with Firebase Authentication:
- In Xcode, enable push notifications for your project.
Upload your APNs certificate to Firebase. If you don't already have an APNs certificate, see Provisioning APNs SSL Certificates.
-
Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.
-
Select the Upload Certificate button for your development certificate, your production certificate, or both. At least one is required.
-
For each certificate, select the .p12 file, and provide the password, if any. Make sure the bundle ID for this certificate matches the bundle ID of your app. Select Save.
-
Receive notifications without swizzling
Firebase Authentication uses method swizzling to automatically obtain your app's APNs token and to handle the silent push notifications that Firebase sends to your app during verification.
If you prefer not to use swizzling, you can disable it by adding the flag
FirebaseAppDelegateProxyEnabled to your app's Info.plist file and
setting it to NO. Note that setting this flag to NO
also disables swizzling for other Firebase products, including
Firebase Cloud Messaging.
If you disable swizzling, you must explicitly pass the APNs device token and push notifications to Firebase Authentication.
To obtain the APNs device token, implement the
application:didRegisterForRemoteNotificationsWithDeviceToken:
method, and in it, pass the device token to FIRAuth's
setAPNSToken:type: method.
Swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass device token to auth
Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenTypeProd)
// Further handling of the device token if needed by the app
// ...
}
Objective-C
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// Pass device token to auth.
[[FIRAuth auth] setAPNSToken:deviceToken type:FIRAuthAPNSTokenTypeProd];
// Further handling of the device token if needed by the app.
}
To handle push notifications, in the
application:didReceiveRemoteNotification:fetchCompletionHandler:
method, check for Firebase auth related notifications by calling
FIRAuth's canHandleNotification: method.
Swift
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(UIBackgroundFetchResultNoData)
return
}
// This notification is not auth related, developer should handle it.
}
Objective-C
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)notification
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Pass notification to auth and check if they can handle it.
if ([[FIRAuth auth] canHandleNotification:notification]) {
completionHandler(UIBackgroundFetchResultNoData);
return;
}
// This notification is not auth related, developer should handle it.
}
Send a verification code to the user's phone
To initiate phone number sign-in, present the user an interface that prompts
them to provide their phone number, and then call
verifyPhoneNumber:completion: to request that Firebase send an
authentication code to the user's phone by SMS:
-
Get the user's phone number.
Legal requirements vary, but as a best practice and to set expectations for your users, you should inform them that if they use phone sign-in, they might receive an SMS message for verification and standard rates apply.
- Call
verifyPhoneNumber:completion:, passing to it the user's phone number.When you callSwift
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { (verificationID, error) in if let error = error { self.showMessagePrompt(error.localizedDescription) return } // Sign in using the verificationID and the code sent to the user // ... }Objective-C
[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) { if (error) { [self showMessagePrompt:error.localizedDescription]; return; } // Sign in using the verificationID and the code sent to the user // ... }];verifyPhoneNumber:completion:, Firebase sends a silent push notification to your app. After your app receives the notification, Firebase sends an SMS message containing an authentication code to the specified phone number and passes a verification ID to your completion function. You will need both the verification code and the verification ID to sign in the user. -
Save the verification ID and restore it when your app loads. By doing so, you can ensure that you still have a valid verification ID if your app is terminated before the user completes the sign-in flow (for example, while switching to the SMS app).
You can persist the verification ID any way you want. A simple way is to save the verification ID with the
NSUserDefaultsobject:Swift
UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
Objective-C
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:verificationID forKey:@"authVerificationID"];
Then, you can restore the saved value:
Swift
let verificationID = UserDefaults.standard.string(forKey: "authVerificationID")
Objective-C
NSString *verificationID = [defaults stringForKey:@"authVerificationID"];
If the call to verifyPhoneNumber:completion: succeeds, you can
prompt the user to type the verification code when they receive it in the SMS
message.
Sign in the user with the verification code
After the user provides your app with the verification code from the SMS
message, sign the user in by creating a FIRPhoneAuthCredential
object from the verification code and verification ID and passing that object
to signInWithCredential:completion:.
- Get the verification code from the user.
- Create a
FIRPhoneAuthCredentialobject from the verification code and verification ID.Swift
let credential = PhoneAuthProvider.provider().credential( withVerificationID: verificationID, verificationCode: verificationCode)Objective-C
FIRAuthCredential *credential = [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID verificationCode:userInput]; - Sign in the user with the
FIRPhoneAuthCredentialobject:Swift
Auth.auth().signIn(with: credential) { (user, error) in if let error = error { // ... return } // User is signed in // ... } }Objective-C
[[FIRAuth auth] signInWithCredential:credential completion:^(FIRUser *user, NSError *error) { if (error) { // ... return; } // User successfully signed in. Get user data from the FIRUser object // ... }];
Next steps
After a user signs in for the first time, a new user account is created and linked to the credentials—that is, the user name and password, phone number, or auth provider information—the user signed in with. This new account is stored as part of your Firebase project, and can be used to identify a user across every app in your project, regardless of how the user signs in.
-
In your apps, you can get the user's basic profile information from the
FIRUserobject. See Manage Users. In your Firebase Realtime Database and Cloud Storage Security Rules, you can get the signed-in user's unique user ID from the
authvariable, and use it to control what data a user can access.
You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account.
To sign out a user, call
signOut:.
Swift
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
Objective-C
NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
NSLog(@"Error signing out: %@", signOutError);
return;
}
You may also want to add error handling code for the full range of authentication errors. See Handle Errors.

