Published on

Firebase authentication with a third-party 0Auth provider

If you are using Firebase but want to log in users with providers other than the list of providers that Firebase supports, you can use the custom token mechanism to do so.

For example, lets say that you want to login users with Discord but Firebase does not support Discord as a provider directly, then you can use this mechanism to log users in with Firebase

You will need to use a server environment like Node.js or Firebase functions since the Firebase admin SDK only works on server environments

Step 0 - Integrate the Firebase admin SDK with whatever env you are using

I am leaving this upto you as there are a lot of ways to do this

Step 1 - Find or Create the user

On the callback of the 0Auth, you will probably get the email that the user used to sign in with. Use that to find if its a new or existing user.

Then if the user does not already exists, create a new user

let userRecord = await firebaseAdmin.auth().getUserByEmail(email)

if (!userRecord) {
  const userRecord = await firebaseAdmin.auth().createUser({
    email: email,
    emailVerified: true,
    disabled: false,
  })
}

Step 2 - Generate the token

Now that you have the required user object, use that to generate a custom token

const customToken = await firebaseAdmin.auth().createCustomToken(userRecord.uid)

Return this custom token to the client

Step 3 - Login on the client

Use the custom token received from the server to log the user in on the client

await firebase.auth().signInWithCustomToken(customToken)

Did you like what you read?

You can follow me on Twitter or LinkedIn to get notified when I publish new content.