I am try to link a Twitter Auth Provider to an email and password account via a flutter application using Firebase. I first want to sign in/up with email and password, then sometime down the road (a few hours, a few days, whenever…) authenticate with a user’s Twitter account and associate it with that email and password account.
The code seems pretty straight forward but whenever I try to call signInWithProvider(TwitterAuthProvider())
followed by linkWithCredential(twitterAuthCredential.credential)
, the current user FirebaseAuth.instance.currentUser
is signed out and replaced with the twitter user and I get an error that indicates the provider is already linked to the current user:
Exception has occurred. FirebaseAuthException ([firebase_auth/provider-already-linked] User has already been linked to the given provider.)
Is the only way to link an account is if it’s during signup/sign in when the credentials are retreived?
I’ve seen the solutions that init different apps but I’m hoping there’s another way.
The option alluded to here – to change providers per email has been moved to Authentication > Settings but the default value is "Link accounts that use the same email"
I’m aware the instructions say "up to but not including the signInWith
calls" but I have limited options of getting the user’s password well after they’ve already logged in, for security reasons, and I can’t store their password, also for security best practices.
The twitter account I’m using, using the same email as the Twitter account.
Thanks,
final currentUser = FirebaseAuth.instance.currentUser; // already logged in with email and password
if (currentUser != null) {
TwitterAuthProvider twitterProvider = TwitterAuthProvider();
UserCredential twitterAuthCredential = await FirebaseAuth.instance.signInWithProvider(twitterProvider);
if (twitterAuthCredential.credential != null) {
await currentUser.linkWithCredential(twitterAuthCredential.credential!);
} else {
debugPrint('Could not link Twitter auth credentials');
}
}
2
Answers
I had to use
linkWithProvider
instead of the example code provided here. I'm guessing the small detail I missed was that I'm not trying to link another Authentication method, I'm just trying to authenticate with another provider so that I can link the providers?The solution that worked for me is as follows (already being logged in with email and password):
Then a Twitter login popped up and I was able to have my email/password associated with Twitter after signing in.
Please read the blog from the provided link. I think it will help you to understand the logic about how you check your email that is already linked or not, and if already link then what to do in switch case based on the return value.
https://firebase.flutter.dev/docs/auth/account-linking