Link Multiple Auth Providers to an Account on Apple Platforms
Stay organized with collections
Save and categorize content based on your preferences.
You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account. Users are identifiable by the same Firebase user ID regardless of the authentication provider they used to sign in. For example, a user who signed in with a password can link a Google account and sign in with either method in the future. Or, an anonymous user can link a Facebook account and then, later, sign in with Facebook to continue using your app.
Before you begin
Add support for two or more authentication providers (possibly including anonymous authentication) to your app.
Link auth provider credentials to a user account
To link auth provider credentials to an existing user account:
- Sign in the user using any authentication provider or method.
- Complete the sign-in flow for the new authentication provider up to, but not
including, calling one of the
FIRAuth.signInWithmethods. For example, get the user's Google ID token, Facebook access token, or email and password. Get a
FIRAuthCredentialfor the new authentication provider:Google Sign-In
Swift
guard letauthentication=user?.authentication, letidToken=authentication.idToken else{ return } letcredential=GoogleAuthProvider.credential(withIDToken:idToken, accessToken:authentication.accessToken)
Objective-C
FIRAuthCredential*credential= [FIRGoogleAuthProvidercredentialWithIDToken:result.user.idToken.tokenString accessToken:result.user.accessToken.tokenString];
Facebook Login
Swift
letcredential=FacebookAuthProvider .credential(withAccessToken:AccessToken.current!.tokenString)
Objective-C
FIRAuthCredential*credential=[FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessTokencurrentAccessToken].tokenString];
Email-password sign-in
Swift
letcredential=EmailAuthProvider.credential(withEmail:email,password:password)
Objective-C
FIRAuthCredential*credential= [FIREmailAuthProvidercredentialWithEmail:email password:password];
Pass the
FIRAuthCredentialobject to the signed-in user'slinkWithCredential:completion:method:Swift
user.link(with:credential){authResult,errorin // ... } }
Objective-C
[[FIRAuthauth].currentUserlinkWithCredential:credential completion:^(FIRAuthDataResult*result,NSError*_Nullableerror){ // ... }];
The call to
linkWithCredential:completion:will fail if the credentials are already linked to another user account. In this situation, you must handle merging the accounts and associated data as appropriate for your app:Swift
letprevUser=Auth.auth().currentUser Auth.auth().signIn(with:credential){authResult,errorin ifleterror=error{ letauthError=errorasNSError ifisMFAEnabled,authError.code==AuthErrorCode.secondFactorRequired.rawValue{ // The user is a multi-factor user. Second factor challenge is required. letresolver=authError .userInfo[AuthErrorUserInfoMultiFactorResolverKey]as!MultiFactorResolver vardisplayNameString="" fortmpFactorInfoinresolver.hints{ displayNameString+=tmpFactorInfo.displayName??"" displayNameString+=" " } self.showTextInputPrompt( withMessage:"Select factor to sign in\n\(displayNameString)", completionBlock:{userPressedOK,displayNamein varselectedHint:PhoneMultiFactorInfo? fortmpFactorInfoinresolver.hints{ ifdisplayName==tmpFactorInfo.displayName{ selectedHint=tmpFactorInfoas?PhoneMultiFactorInfo } } PhoneAuthProvider.provider() .verifyPhoneNumber(with:selectedHint!,uiDelegate:nil, multiFactorSession:resolver .session){verificationID,errorin iferror!=nil{ print( "Multi factor start sign in failed. Error: \(error.debugDescription)" ) }else{ self.showTextInputPrompt( withMessage:"Verification code for \(selectedHint?.displayName??"")", completionBlock:{userPressedOK,verificationCodein letcredential:PhoneAuthCredential?=PhoneAuthProvider.provider() .credential(withVerificationID:verificationID!, verificationCode:verificationCode!) letassertion:MultiFactorAssertion?=PhoneMultiFactorGenerator .assertion(with:credential!) resolver.resolveSignIn(with:assertion!){authResult,errorin iferror!=nil{ print( "Multi factor finanlize sign in failed. Error: \(error.debugDescription)" ) }else{ self.navigationController?.popViewController(animated:true) } } } ) } } } ) }else{ self.showMessagePrompt(error.localizedDescription) return } // ... return } // User is signed in // ... } // Merge prevUser and currentUser accounts and data // ... }
Objective-C
FIRUser*prevUser=[FIRAuthauth].currentUser; [[FIRAuthauth]signInWithCredential:credential completion:^(FIRAuthDataResult*_NullableauthResult, NSError*_Nullableerror){ if(isMFAEnabled && error && error.code==FIRAuthErrorCodeSecondFactorRequired){ FIRMultiFactorResolver*resolver=error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey]; NSMutableString*displayNameString=[NSMutableStringstring]; for(FIRMultiFactorInfo*tmpFactorInfoinresolver.hints){ [displayNameStringappendString:tmpFactorInfo.displayName]; [displayNameStringappendString:@" "]; } [selfshowTextInputPromptWithMessage:[NSStringstringWithFormat:@"Select factor to sign in\n%@",displayNameString] completionBlock:^(BOOLuserPressedOK,NSString*_NullabledisplayName){ FIRPhoneMultiFactorInfo*selectedHint; for(FIRMultiFactorInfo*tmpFactorInfoinresolver.hints){ if([displayNameisEqualToString:tmpFactorInfo.displayName]){ selectedHint=(FIRPhoneMultiFactorInfo*)tmpFactorInfo; } } [FIRPhoneAuthProvider.provider verifyPhoneNumberWithMultiFactorInfo:selectedHint UIDelegate:nil multiFactorSession:resolver.session completion:^(NSString*_NullableverificationID,NSError*_Nullableerror){ if(error){ [selfshowMessagePrompt:error.localizedDescription]; }else{ [selfshowTextInputPromptWithMessage:[NSStringstringWithFormat:@"Verification code for %@",selectedHint.displayName] completionBlock:^(BOOLuserPressedOK,NSString*_NullableverificationCode){ FIRPhoneAuthCredential*credential= [[FIRPhoneAuthProviderprovider]credentialWithVerificationID:verificationID verificationCode:verificationCode]; FIRMultiFactorAssertion*assertion=[FIRPhoneMultiFactorGeneratorassertionWithCredential:credential]; [resolverresolveSignInWithAssertion:assertioncompletion:^(FIRAuthDataResult*_NullableauthResult,NSError*_Nullableerror){ if(error){ [selfshowMessagePrompt:error.localizedDescription]; }else{ NSLog(@"Multi factor finanlize sign in succeeded."); } }]; }]; } }]; }]; } elseif(error){ // ... return; } // User successfully signed in. Get user data from the FIRUser object if(authResult==nil){return;} FIRUser*user=authResult.user; // ... }]; // Merge prevUser and currentUser accounts and data // ... }];
If the call to linkWithCredential:completion: succeeds, the user can now sign in using
any linked authentication provider and access the same Firebase data.
Unlink an auth provider from a user account
You can unlink an auth provider from an account, so that the user can no longer sign in with that provider.
To unlink an auth provider from a user account, pass the provider ID to the
unlink method. You can get the provider IDs
of the auth providers linked to a user from the providerData
property.
Swift
Auth.auth().currentUser?.unlink(fromProvider:providerID!){user,errorin // ... }
Objective-C
[[FIRAuthauth].currentUserunlinkFromProvider:providerID completion:^(FIRUser*_Nullableuser,NSError*_Nullableerror){ // ... }];
Troubleshooting
If you encounter errors when trying to link multiple accounts, see the documentation on verified email addresses.