Home > Back-end >  How to authenticate to Firebase after logging in to Facebook on an Ionic 5 - Capacitor application
How to authenticate to Firebase after logging in to Facebook on an Ionic 5 - Capacitor application

Time:03-07

Having an Ionic Angular application, I added the Capacitor plugin to log into Facebook and I receive the user and the token. The problem is that I cannot connect to Firebase and create a session.

My packets are:

"@angular/common": "~12.1.1",
"@angular/fire": "^7.2.0",
"@capacitor-community/facebook-login": "^3.1.1",
"@capacitor/core": "3.3.1",
"@ionic/angular": "^5.5.2",
"firebase": "^9.6.2",
...

I have tried with no succes the following:

  • signInWithPopup - works on browser - does not work on device
  • signInWithRedirect - the same
  • signInWithCredential - signing in with a custom token - I get an error that the token is not right
  • signInWithCustomToken - the same

These packets I importe from '@angular/fire/auth';

CodePudding user response:

I recommend you to use a Capacitor plugin for this, which implements the Firebase SDK.

Example: https://github.com/robingenz/capacitor-firebase-authentication

import { FirebaseAuthentication } from '@robingenz/capacitor-firebase-authentication';

const signInWithFacebook = async () => {
  await FirebaseAuthentication.signInWithFacebook();
};

If you want to use it together with the Firebase JavaScript SDK:

import { FirebaseAuthentication } from '@robingenz/capacitor-firebase-authentication';
import {
  getAuth,
  FacebookAuthProvider,
  signInWithCredential,
} from 'firebase/auth';


const signInWithFacebook = async () => {
  // 1. Create credentials on the native layer
  const result = await FirebaseAuthentication.signInWithFacebook();
  // 2. Sign in on the web layer using the access token
  const credential = FacebookAuthProvider.credential(
    result.credential?.accessToken,
  );
  const auth = getAuth();
  await signInWithCredential(auth, credential);
};

CodePudding user response:

Thanks to @RGe I managed to figure it out.

The solution is like this:

import { FacebookLogin, FacebookLoginResponse } from '@capacitor-community/facebook-login';
import { getAuth, FacebookAuthProvider, signInWithCredential } from '@angular/fire/auth';

...

export class LoginPage implements OnInit {
    async doFbLogin() {
      const FACEBOOK_PERMISSIONS = ['email', 'user_birthday', 'user_photos', 'user_gender'];
      const result: FacebookLoginResponse = await FacebookLogin.login({ permissions: FACEBOOK_PERMISSIONS });
      ....
      const credential = FacebookAuthProvider.credential(result.accessToken.token);
      const auth = getAuth();
      signInWithCredential(auth, credential).then... // here is the Firebase auth

    }

}
  • Related