Link Facebook to Firebase Anonymous Auth without calling Facebook API

426 views
Skip to first unread message

ky...@patronage.org

unread,
Jul 1, 2016, 4:42:10 PM7/1/16
to Firebase Google Group

I am creating anonymous sessions in my Firebase application to save user data before they create their accounts. I saw that Firebase allows linking a Facebook login to an anonymous account which sounds really neat, but a caveat of this process seems to be that I have to grab the Facebook token myself, outside the warmth and comfort of the awesome Firebase API, which seems strange given how much of the login flow Firebase seems to do on behalf of apps.

A code sample of how to connect an anonymous account from their account linking docs:

var credential = firebase.auth.FacebookAuthProvider.credential(
    response.authResponse.accessToken);

Naturally, I want to use Firebase's way of getting a token

var provider = new firebase.auth.FacebookAuthProvider();

firebase.auth().signInWithPopup(provider).then(function(result) {
     // result.token or whatever would appear here
});

But if I were to run that, I would lose my anonymous session (and my anonymous user ID, which we want the new Facebook login to use).

Is there anyway to get a Facebook Token out of Firebase's auth mechanism without logging the user in and losing the anonymous session that I'm trying to convert into a Facebook Login-able account? (The goal is to not have to call the Facebook API myself, especially as I'll be adding Google here as well)

Thanks, Kyle

Bassam Ojeil

unread,
Jul 1, 2016, 10:00:35 PM7/1/16
to Firebase Google Group
Hey Kyle, you have 2 options:
firebase.auth().signInAnonymously()
1.  This is the ideal solution for your case but has one caveat,
var provider = new firebase.auth.FacebookAuthProvider();
Then call firebase.auth().currentUser.linkWithPopup(provider);
This will upgrade the anonymous user to a facebook one while keep all the user's data (same user id too obviously).
The only downside here is that if the facebook user was already created (existing firebase user), an error will be thrown. and you will need to login the facebook user again with popup) which is not great UX. 
2. Get the facebook access token using the facebook sdk.
Then call the following on the anonymous current user:
firebase.auth().link(firebase.auth.FacebookAuthProvide.credential(facebookAccessToken));
If the user does not exist, it will work expectedly. If not, it will return the same error as the above. You can then call the following to sign in the facebook user:
firebase.auth().signInWithCredential(firebase.auth.FacebookAuthProvide.credential(facebookAccessToken));

When the account exists, you have to merge the data on you own.

Hopefully this answers your question.

Bassam
Reply all
Reply to author
Forward
0 new messages