Is it Possible to Build a Chrome Extension Supporting Login via web3Auth Using Firebase Authentication?

Hello everyone,

I’m currently working on a Chrome extension and am trying to implement user authentication using web3Auth integrated with Firebase Authentication. However, I’ve been facing some challenges during the process.

Problem: Upon trying to authenticate, I encounter an error related to URL redirecting, mentioning that the key from web3Auth cannot be initialized. This seems to be a unique issue arising from the interaction between a Chrome extension’s environment and the web3Auth-Firebase integration.

Details:

  1. I’ve set up Firebase Authentication correctly, and it works as expected in a standard web environment.
  2. When the Firebase authentication flow triggers in the extension, the redirect URL seems to be causing issues.
  3. I suspect that this might be related to the specific nature of URLs within Chrome extensions and the way web3Auth expects to handle redirects and initialize keys.

Question: Has anyone here successfully integrated web3Auth with Firebase Authentication within a Chrome extension? If so, could you provide insights or guidance on how to resolve the redirect URL and key initialization issue?

Any help or pointers would be greatly appreciated!

As seen in this image, although the id of firebase return but I can connect to web3 sdk

@toanbt Welcome Aboard!

Your request is under review and we will get back with further updates.

Once initialized, and idToken is obtained from Firebase, are you using the connectTo() function to authenticate the user with Web3Auth?

import { WALLET_ADAPTERS, CHAIN_NAMESPACES } from "@web3auth/base";

await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
  loginProvider: "jwt",
  extraLoginOptions: {
    id_token: idToken,
    verifierIdField: "sub", // same as your JWT Verifier ID
    domain: "https://YOUR-APPLICATION-DOMAIN" || "http://localhost:3000",
  },
});

When connecting, your connectTo function takes the arguments for the adapter you want to connect to and the options for the login. Few major things to note here is the idToken and domain option in the extraLoginOptions object. This is the idToken received from Firebase SDK and domain is your application domain so that you can be redirected after login from the Web3Auth Plug and Play No Modal SDK.

Can you share your complete implementation code?

1 Like

Sure. Here is my full code.
I’m working on a Chrome extension where I’ve integrated user authentication via Firebase, specifically using Google login. While the authentication works fine, I’m encountering an issue with the post-login redirection to web3Auth.

In a standard web application environment, after successful authentication with Google via Firebase, it seamlessly redirects to web3Auth. However, within the context of my Chrome extension, this redirection doesn’t seem to work as expected.

import React, { useCallback, useEffect, useState } from 'react';
import Layout from './components/layout';
import { useHistory } from 'react-router-dom';

import { useTranslation, Trans } from 'react-i18next';
import Button from '@material-ui/core/Button';

import { makeStyles } from '@material-ui/core';
import { useWeb3Auth } from './Web3AuthProvider/useWeb3Auth';
import { initializeApp } from 'firebase/app';
import { GoogleAuthProvider, getAuth, signInWithPopup, UserCredential } from 'firebase/auth';
import { firebaseConfig } from '../../common/constant/web3-auth';
import { WALLET_ADAPTERS } from '@web3auth/base';

interface Props {}

const FirstTimeUser: React.FC<Props> = (props) => {
  const { t } = useTranslation();
  const classes = useStyles();
  const history = useHistory();
  const [init, setInit] = useState(false);
  const { web3auth, loggedIn } = useWeb3Auth();

  const onLoginWithLocal = useCallback(() => {
    history.push('/welcome');
  }, [history]);

  const signInWithGoogle = async (): Promise<UserCredential> => {
    try {
      const app = initializeApp(firebaseConfig);
      const auth = getAuth(app);
      const googleProvider = new GoogleAuthProvider();
      const res = await signInWithPopup(auth, googleProvider);
      return res;
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const onLoginByWeb3Auth = useCallback(async () => {
    if (web3auth) {
      try {
        const loginRes = await signInWithGoogle();
        const idToken = await loginRes.user.getIdToken(true);
        console.log('idToken: ', idToken);
        try {
          const web3authProvider = await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
            loginProvider: 'jwt',
            extraLoginOptions: {
              id_token: idToken,
              verifierIdField: 'sub',
              domain: 'chrome-extension://gnbdhaacjahjgemacgkdfphhlhhjkjj',
            },
          });
          const userInfo = await web3auth.getUserInfo();
        } catch (error) {
          console.log('error: ', error);
        }
      } catch (error) {
        console.error('Failed to connect with Web3Auth', error);
      }
    }
  }, [history, web3auth]);

Please add chrome-extension://{extension-id} in the whitelist section of your project on the Web3auth dashboard.

I would like to inquire whether your project is currently on testnet or sapphire_devnet? Try setting your project on testnet, and consider changing the network to testnet in your code as well.

Can you take a look at our example for Chrome browser extension. Be sure to include your Client ID and ensure the network is the same at the project you have setup:

1 Like

Hi,
First and foremost, I want to express my gratitude for your swift response. I’ve closely followed the steps you provided and wanted to assure you that I’ve already added chrome-extension://{extension-id} to the whitelist section of our project on the Web3auth dashboard.

Additionally, our project is currently set to the sapphire. I’ve double-checked the network configuration in our code to ensure it aligns with our project setup.

Regarding the example for the Chrome browser extension, I’ve made certain to include our Client ID and matched the network settings as per the setup on our project.

import React, { createContext, useEffect, useState, ReactNode } from 'react';
import { Web3AuthNoModal } from '@web3auth/no-modal';
import { CHAIN_NAMESPACES, IProvider } from '@web3auth/base';
import { clientId } from '../../../common/constant/web3-auth';
import { EthereumPrivateKeyProvider } from '@web3auth/ethereum-provider';
import { OpenloginAdapter } from '@web3auth/openlogin-adapter';

interface Web3AuthContextType {
  web3auth: Web3AuthNoModal | null;
  provider: IProvider | null;
  loggedIn: boolean;
  logout: () => void;
}

export const Web3AuthContext = createContext<Web3AuthContextType | null>(null);

interface Web3AuthProviderProps {
  children: ReactNode;
}

export const Web3AuthProvider: React.FC<Web3AuthProviderProps> = ({ children }) => {
  const [web3auth, setWeb3auth] = useState<Web3AuthNoModal | null>(null);
  const [provider, setProvider] = useState<IProvider | null>(null);
  const [loggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    const init = async () => {
      try {
        const chainConfig = {
          chainNamespace: CHAIN_NAMESPACES.EIP155,
          chainId: '0x5', // Please use 0x1 for Mainnet
          rpcTarget: 'https://rpc.ankr.com/eth_goerli',
          displayName: 'Goerli Testnet',
          blockExplorer: 'https://goerli.etherscan.io/',
          ticker: 'ETH',
          tickerName: 'Ethereum',
        };
        const web3auth = new Web3AuthNoModal({
          clientId,
          chainConfig,
          web3AuthNetwork: 'sapphire_devnet',
          useCoreKitKey: false,
        });

        const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });
        const openloginAdapter = new OpenloginAdapter({
          privateKeyProvider,
          adapterSettings: {
            uxMode: 'redirect',
            loginConfig: {
              jwt: {
                verifier: 'gu-wallet-firebase',
                typeOfLogin: 'jwt',
                clientId,
              },
            },
          },
        });
        web3auth.configureAdapter(openloginAdapter);
        setWeb3auth(web3auth);

        await web3auth.init();
        const status = await web3auth.status;
        console.log('status: ', status);
        setProvider(web3auth.provider);
        if (web3auth.connected) {
          setLoggedIn(true);
        }
      } catch (error) {
        console.error(error);
      }
    };
    init();
  }, []);

  const logout = async () => {
    if (web3auth) {
      await web3auth.logout();
      setLoggedIn(false);
    }
  };

  return (
    <Web3AuthContext.Provider value={{ web3auth, provider, loggedIn, logout }}>
      {children}
    </Web3AuthContext.Provider>
  );
};

And here is config at Web3Dashboard

Thanks for your reply.

Can you confirm that you are able to get the chrome extension example I provided working at your end ?

Hi, I just checked and built the chrome extension you mentioned above and it worked properly. But my project use firebase login and I customized authentication at web3Auth Dashboard but it seem like after logged in google it not redirect to ‘authweb3.io’.

Which network did you use for the example? sapphire_devnet?

Hi,
To clarify, for our main project, we’re using the sapphire_devnet . However, for the example, we’ve set it to the devnet . Both of main project and example, I initialized Goerli network as chain config. Is any different between ‘sapphire_devnet’ and ‘devnet’ ?

The only Web3Auth networks are testnet , mainnet , aqua , cyan , sapphire_devnet , and sapphire_mainnet. Can you check if you are able to setup up your project with testnet instead of sapphire-devnet to get it working with your firebase/chrome implementation?

1 Like

Thank you for clarifying the available networks for Web3Auth.

I’ll go ahead and set up our project with the testnet instead of the sapphire_devnet to see if that resolves the issue with our firebase/chrome implementation. I appreciate the guidance.

Should I have further questions or require additional assistance, I’ll reach out to you.

Wishing you a great day ahead!

@toanbt I wanted to check if you are still facing any issues?

Hi,
I’m still facing with this issues. After getting successfully id_token from firebase then I call function

    const web3authProvider = await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
      loginProvider: 'jwt',
      extraLoginOptions: {
        id_token: idToken,
        verifierIdField: 'sub',
        domain: '',
      },
    });

but it not redirect to torus website for initializing key and close popup.

  useEffect(() => {
    const init = async () => {
      try {
        const chainConfig = {
          chainNamespace: CHAIN_NAMESPACES.EIP155,
          chainId: '0x5', // Please use 0x1 for Mainnet
          rpcTarget: 'https://rpc.ankr.com/eth_goerli',
          displayName: 'Goerli Testnet',
          blockExplorer: 'https://goerli.etherscan.io/',
          ticker: 'ETH',
          tickerName: 'Ethereum',
        };
        const web3auth = new Web3AuthNoModal({
          clientId,
          chainConfig,
          web3AuthNetwork: 'testnet',
          useCoreKitKey: false,
        });

        const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });
        const openloginAdapter = new OpenloginAdapter({
          privateKeyProvider,
          adapterSettings: {
            uxMode: 'redirect',
            loginConfig: {
              jwt: {
                verifier: 'macos-firebase',
                typeOfLogin: 'jwt',
                clientId,
              },
            },
          },
        });
        web3auth.configureAdapter(openloginAdapter);
        await web3auth.init();
        setWeb3auth(web3auth);
        const status = await web3auth.status;
        console.log('status: ', status);
      } catch (error) {
        console.error(error);
      }
    };
    init();
  }, []);

This is my init function web3authNoModal

Hi,
I just solved problem with redirect to “Web3Auth”. Now I’m facing with issue


Do you know which config is wrong base on this image

1 Like

Hey @toanbt, I see you’re not specifying verifierIdField in connectTo method as seen in this example.
Please specify the same verifierIdField as you have specified while setting up the verifier.

Hi, I surely specified the same ‘verifierIdField’ as I have specified in web3AuthDashboard.
Here is my method loginByWeb3Auth

const signInWithGoogle = async (): Promise<UserCredential> => {
    try {
      const app = initializeApp(firebaseConfig);
      const auth = getAuth(app);
      console.log('ath: ', auth);
      const googleProvider = new GoogleAuthProvider();
      console.log('googleProvider: ', googleProvider);
      const res = await signInWithPopup(auth, googleProvider);
      return res;
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

  const loginByWeb3Auth = useCallback(async () => {
    if (!web3auth) {
      return;
    }
    const loginRes = await signInWithGoogle();
    const idToken = await loginRes.user.getIdToken(true);
    console.log('idToken', idToken);
    console.log('web3auth', web3auth);

    const web3authProvider = await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
      loginProvider: 'jwt',
      extraLoginOptions: {
        id_token: idToken,
        verifierIdField: 'sub',
        domain: 'chrome-extension://ffapoeiemcnagljekokcpfpcockhbbbc',
      },
    });
    const userInfo = await web3auth.getUserInfo();
    console.log('userInfo: ', userInfo);
    console.log('web3authProvider: ', web3authProvider);
  }, [web3auth]);

And here is config in web3Dashboard

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.