Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Chrome Extension get user credential from Firebase web app without user having to sign in twice?

I have both a Firebase web app and a Chrome Extension - user will use Chrome Extension to save article that can be read later from their web app.

For web app, I use Firebase Auth. But I am unsure how to pass user token or id to Chrome Extension, so that user does not need to login twice.

I have read this question, but it is not clear to me how to send token to Chrome Extension from web app.

Thanks!

like image 355
kadenza Avatar asked Oct 28 '25 03:10

kadenza


1 Answers

There's a detailed answer with examples in this github post

Short scheme is following:

  1. Create cloud function that generates custom firebase token
  2. In web app upon login request a custom token from the cloud function
  3. Using chrome API send message to extension
  4. In extension on message use token to log into firebase
  5. In extension listen to firebase auth state change to log out

Details from post:

Firebase function / Auth Server

In a Firebase function (or a custom server) handle the token creation using firebase function createCustomToken

const admin = require('firebase-admin')
const functions = require('firebase-functions')

admin.initializeApp()

module.exports functions.https.onCall(uid =>
  admin.auth().createCustomToken(uid)
)

Webapp

After a successful login, request the server for a custom Token passing the uid of the logged user

firebase.functions().httpsCallable('createToken')(uid)

Then send it to the chrome extension

chrome.runtime.sendMessage(extensionID, token)

Extension

Finally in the extension when receiving a message, log the user with firebase using the custom token

firebase.initializeApp(firebaseConfig)

firebase.auth().onAuthStateChanged(function (user) {
  console.log(
    'User state change detected from the Background script of the Chrome Extension:',
    user
  )
})

chrome.runtime.onMessageExternal.addListener(
  (token, sender, sendResponse) => {
    firebase
      .auth()
      .signInWithCustomToken(token)
      .catch((error) => {
        console.log('error', error)
      })
    return true
  }
)

Your background script will log the authStateChanged event where you can see that the auth is not isAnonymous anymore and the email attributes is the one of the user logged through your app !

like image 159
Tony Popov Avatar answered Oct 30 '25 17:10

Tony Popov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!