Firebase authentication using google/facebook with custom nodejs server

Viewed 219

I am trying to integrate firebase authentication with my custom nodejs server. The email/password strategy is pretty straightforward as the admin sdk supports all the operations needed. However in the case of providers, the documentation instructs us to Handle the sign-in flow manually and get some token from either google or facebook and then send it to our nodejs server. So when the token arrives to our nodejs server the documentation provides some code that comes from the client sdk.

This is a sample from the firebase documentation

import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";

// Build Firebase credential with the Google ID token.
const credential = GoogleAuthProvider.credential(id_token);

// Sign in with credential from the Google user.
const auth = getAuth();
signInWithCredential(auth, credential).catch((error) => {
  // Handle Errors here.
  const errorCode = error.code;
  const errorMessage = error.message;
  // The email of the user's account used.
  const email = error.customData.email;
  // The AuthCredential type that was used.
  const credential = GoogleAuthProvider.credentialFromError(error);
  // ...
});

where the id_token (probably) comes from the request body.

This flow works just fine but it is using the client sdk in a nodejs server environment because the admin sdk that is inteded for such an environment does not support this kind of operation. So, is it ok to use both SDKs, where it is needed of course, in a nodejs server?

EDIT:

What I am trying to achieve is that when the google id_token (or facebook access token) arrives in my nodejs server I need to have a way to create an account in firebase auth module with the respective provider. So with the signInWithCredential if the user does not exist then will be created and then I will issue a custom token just like I do with the email/password strategy. The only difference here is that with email/password strategy I can use the admin SDK's createUser() for the user creation.

Is this approach right?

1 Answers

Your approach is absolutely right :

1- You recieve google ID token from client (OAuth or etc...)

2- Sign in user to firebase using google ID:

//1 import firebase/auth 

import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";

//2 configue user credentials 

const credential = GoogleAuthProvider.credential(id_token);

//3 run signInWithCredential function

let userData = await signInWithCredential(auth, credential)

Related