Using Firebase with Web3Auth
This guide will cover the basics of how to set up your Web3Auth SDK and Firebase for the integration and provide you with the links on how to develop a basic web application on the Ethereum blockchain.
Quick Start
npx degit Web3Auth/web3auth-pnp-examples/web-no-modal-sdk/custom-authentication/firebase-react-no-modal-example w3a-firebase-demo && cd w3a-firebase-demo && npm install && npm run start
How it works?
When integrating Web3Auth with Firebase, the login flow looks something like this:
When a user logs in with
Firebase
, Firebase sends a JWTid_token
to the app. This JWT token is sent to the Web3Auth SDK's login function.Finally, on successful validation of the JWT token, Web3Auth SDK will generate a private key for the user, in a self custodial way, resulting in easy onboarding for your user to the application.
Prerequisites
For Web Apps: A basic knowledge of JavaScript is required to use Web3Auth SDK.
For Mobile Apps: For the Web3Auth Mobile SDKs, you have a choice between iOS, Android, React Native & Flutter. Please refer to the Web3Auth SDK Reference for more information.
Create a Web3Auth account on the Web3Auth Dashboard
A Firebase account to be used as Federated Identity Provider.
A Google Developer account to be used as Identity provider for Firebase.
Setup
Setup Firebase
- Go to your Firebase console and create a Web App. Follow this guide on how to setup your Firebase Web App project.
Create a Firebase Project
Create a new project by clicking on Add project or use your existing project from Firebase console.
Give your project a name and click on Continue
Finally, click on Create Project
Select Authentication Provider
Once the project is created. Set up authentication by clicking on the Authentication card from the home screen of your project or choose Authentication under Build from the left sidebar.
From Sign-in method tab, select any provider you wish to enanle. For the purpose of this guide, we'll be enabling Google.
Finally, toggle the enable button and click on Save
Configure Firebase for Web
Once the project is created and authentication is configured. Let's use Firebase for Web by clicking on the
</>
button on the home screen of your project.In the next screen, enter the App nickname and click on Register button to register the app for Web.
Next screen shows ways to add Firebase to your application. We will be using the config from here later in the guide. Please keep a note of the
firebaseConfig
object.
Setup Web3Auth
Setup Web3Auth Project
Create a Project from the Project Section of the Web3Auth Developer Dashboard.
Enter your desired Project name.
Select the Product you want to use. For this guide, we'll be using the Plug n Play product.
Select the Platform type you want to use. For this guide, we'll be using the Web Application as the platform.
Select the Web3Auth Network as
Sapphire Devnet
. We recommend creating a project in thesapphire_devnet
ortesnet
network during development. While moving to a production environment, make sure to convert your project tosapphire_mainnet
or any of the legacy mainnet networkmainnet
,aqua
, orcyan
network. Otherwise, you'll end up losing users and keys.Select the blockchain(s) you'll be building this project on. For interoperability with Torus Wallets, you have the option of allowing the user's private key to be used in other applications using Torus Wallets (EVM, Solana, XRPL & Casper).
Finally, once you create the project, you have the option to whitelist your URLs for the project. Please whitelist the domains where your project will be hosted.
Setup Firebase Custom Authentication Verifier
Create a Firebase Verifier from the Custom Authentication tab of your Web3Auth Project.
Click on the
Custom Authentication
tab of your Web3Auth Project.Click on the
Create Verifier
button.Enter a name of your choice for the verifier identifier.
eg. w3a-firebase-demo
Select
Custom Providers
from Choose a Login Provider section.JWKS Endpoint: Enter
https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com
as the JWKS endpoint for the Firebase.Now you have the option to paste a sample idToken(JWT) to get the fields for the JWT validation. This step is optional, but if you have a sample JWT you can paste it here to get the fields for the JWT validation. You can also skip this step and fill in the fields manually.
The following are the JWT validation fields needed for the Firebase JWT validation:
- Type
iss
as a field andhttps://securetoken.google.com/FIREBASE-PROJECT-ID
as a value. - Next, type
aud
as a field andFIREBASE-PROJECT-ID
as a value.
Note: Replace the
FIREBASE-PROJECT-ID
with your Firebase Project ID.- Type
Next, Select
Sub
,Email
or aCustom
value from the dropdown for the JWT Verifier ID. This is the field that will be used as the verifier ID for the user, and it has to be unique for each user.Finally, Click on the
Create
button to create your verifier.
It may take up to 10 minutes to deploy the verifier on sapphire_devnet. You'll receive an email once it's complete.
Using the Web3Auth SDK with Firebase
To use the Web3Auth SDK, you need to add the dependency of the respective platform SDK of Web3Auth to your project. To know more about the available SDKs, please have a look at this documentation page.
For this guide here, we will be talking through the Web3Auth Plug and Play No Modal SDK and using the OpenLogin Provider alongside it to enable Custom Authentication through Firebase.
Setting up your base project for using Web3 libraries:
If you are starting from scratch, to set up this project locally, you will need to create a base Web application, where you can install the required dependencies. However, while working with Web3, there are a few base libraries, which need additional configuration. This is because certain packages are not available in the browser environment, and we need to polyfill them manually. You can follow this documentation where we have mentioned the configuration changes for some popular frameworks for your reference.
Installation
For this project, you need to add the following Web3Auth dependencies to your package.json
npm install --save @web3auth/no-modal @web3auth/openlogin-adapter @web3auth/base web3 firebase
Understanding the Dependencies
- Web3Auth Dependencies
- Web3 Libraries
- Firebase SDK
Web3Auth Dependencies
@web3auth/no-modal
This is the main Core package that contains the Web3Auth SDK.
npm install --save @web3auth/no-modal
@web3auth/openlogin-adapter
For using Custom Authentication, we need to use the OpenLogin Adapter, where we can initialise the authentication details.
npm install --save @web3auth/openlogin-adapter
@web3auth/base
Since we're using typescript, we need the @web3auth/base
package to provide types of the different variables we'll be using throughout the app
building process. This reduces errors to a very large extent.
npm install --save @web3auth/base
Web3 Libraries
web3
/ ethers
/ @solana/web3.js
According to your preference, you can choose to install the web3
or ethers
libraries, to talk to the EVM compatible blockchains under the hood.
For Solana, @solana/web3.js
is the recommended choice.
We'll be using web3
for this guide.
npm install --save web3
Initialization
Once installed, your Web3Auth application needs to be initialized. Initialization is a 4 step process where we add all the config details for Web3Auth:
- Instantiation
- Configuration of Adapters
- Configuration of Plugins
- Initialization of the Web3Auth
Please make sure all of this is happening in your application constructor. This makes sure that Web3Auth is initialised when your application starts up.
For this guide, we're only focusing on the Instantiation, Configuration for the Openlogin Adapter (the default adapter that enables social logins) and Initialization of the Web3Auth SDK. To know more about the other things you can do with Web3Auth, checkout our SDK Reference.
Instantiating Web3Auth
Importing the packages
import { WALLET_ADAPTERS, CHAIN_NAMESPACES, IProvider } from "@web3auth/base";
import { Web3AuthNoModal } from "@web3auth/no-modal";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
Alongside the Web3Auth
and OpenloginAdapter
you need the above mentioned packages from @web3auth/base
for different initialisations mentioned
further in this guide.
Instantiate the Web3Auth SDK
import { Web3AuthNoModal } from "@web3auth/no-modal";
import { CHAIN_NAMESPACES } from "@web3auth/base";
const chainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/eth",
displayName: "Ethereum Mainnet",
blockExplorer: "https://etherscan.io",
ticker: "ETH",
tickerName: "Ethereum",
};
const web3auth = new Web3AuthNoModal({
clientId: "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ",
web3AuthNetwork: "sapphire_mainnet",
chainConfig,
});
Here, we're using the chainConfig
property to set the chainId and chainNamespace. The chainId
and chainNamespace
are the id and the namespace
respectively of the chain you're connecting to. We've initialized them for EVM for this guide. You can find the list of available providers
here to select from.
Additionally, sometimes you might face clogging in the network, due to the fact that the test network is a bit clogged at that point. To avoid this,
we can use the property rpcTarget
and pass over the URL of the node you want to connect to.
Initialize Firebase with Firebase configuration
// Import the functions you need from the SDK
import { initializeApp } from "firebase/app";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDEfyUmXDhgGWibRUro2EBoX8-TtBKMYyA",
authDomain: "web3auth-x-firebase-demo-e3332.firebaseapp.com",
projectId: "web3auth-x-firebase-demo-e3332",
storageBucket: "web3auth-x-firebase-demo-e3332.appspot.com",
messagingSenderId: "108145034076",
appId: "1:108145034076:web:3ff4c0088ec4c311b17799",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
Import initializeApp
from the Firebase SDK and use the firebaseConfig obtained above to initialize the Firebase web app.
Initialising the Openlogin Adapter
const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });
const openloginAdapter = new OpenloginAdapter({
adapterSettings: {
uxMode: "redirect", // redirect or popup
loginConfig: {
jwt: {
verifier: "w3a-firebase-demo", // name of the verifier created on Web3Auth Dashboard
typeOfLogin: "jwt",
clientId: "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ",
},
},
},
privateKeyProvider,
});
web3auth.configureAdapter(openloginAdapter);
Here, you need to pass over your Web3Auth clientId
in the adapterSettings object and your Custom Auth verifierName
in the loginConfig object. This
makes sure that the Openlogin Adapter can connect to the correct verifier and Firebase server.
Initialising the Web3Auth SDK
await web3auth.init();
Initialising on Mobile Platforms
- For Mobile, depending on the platform, there will be different steps to initialize the SDK. Refer to the respective Mobile SDKs,
Authentication
Login is a two step process:
- Firstly, we will login with Firebase(Google) to get the
idToken
. - Next, we will pass the received
idToken
to web3auth to login via Web3Auth SDK to generate the public-private key pair for easier onboarding to Web3.
Login with Firebase
import { GoogleAuthProvider, getAuth, signInWithPopup, UserCredential } from "firebase/auth";
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 (err) {
console.error(err);
throw err;
}
};
const loginRes = await signInWithGoogle();
const idToken = await loginRes.user.getIdToken(true); // this idToken will be passed to web3auth
Login with Web3Auth
Once initialized, and idToken
is obtained from Firebase, you can use the connectTo()
function to authenticate the user with Web3Auth.
import { WALLET_ADAPTERS } from "@web3auth/base";
await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
loginProvider: "jwt",
extraLoginOptions: {
id_token: idToken,
verifierIdField: "sub", // same as your JWT Verifier ID field
},
});
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.
Get the User Profile
const user = await web3auth.getUserInfo();
console.log("User info", user);
Using the getUserInfo
function, you can get the details of the logged in user. Please note that these details are not stored anywhere in Web3Auth
network, but are fetched from the id_token you received from Firebase and lives in the frontend context.
Logout
Logging out your user is as simple as calling the logout
function.
await web3auth.logout();
Interacting with Blockchain
So if you have completed this far, it means that you have successfully authenticated your user. Now, you can use the provider returned by Web3Auth as
web3auth.provider
to interact with your blockchain. You can use the Provider SDKs to perform RPC Calls to your
blockchain.
Web3Auth is chain agnostic, ie. depending on whatever blockchain or layer-2 you use, Web3Auth can easily support that. Web3Auth has native providers
for EVM and Solana blockchains and for others, you can get the private key in the user scope and make RPC calls. For standardising the type of
provider, Web3Auth Base provides a IProvider
from which you can create your own provider.
- Ethereum Provider gives you the capability of making RPC calls to the EVM compatible blockchains.
- Solana Provider gives you the capability of making RPC calls to the Solana blockchain.
- XRPL Provider gives you the capability of making RPC calls to the XRPL blockchain.
- If you want to use any other chain except Solana or EVM chains, for ex: Starknet, you can specify the value of
chainNamespace
field as other in the Web3Auth SDK Constructor. Refer to: Using other blockchains
Get User Accounts
- Web3
- Ethers.js
const getAccounts = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const web3 = new Web3(provider as any);
const userAccounts = await web3.eth.getAccounts();
console.log(userAccounts);
};
const getAccounts = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const provider = new ethers.providers.Web3Provider(provider as any);
const signer = provider.getSigner();
const userAccounts = await signer.getAddress();
console.log(userAccounts);
};
View User Balance
- Web3
- Ethers.js
const getBalance = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const web3 = new Web3(provider as any);
const accounts = await web3.eth.getAccounts();
const balance = await web3.eth.getBalance(accounts[0]);
console.log(web3.utils.fromWei(balance));
};
const getBalance = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const provider = new ethers.providers.Web3Provider(this.provider as any);
const signer = provider.getSigner();
const account = await signer.getAddress();
// Get user's balance in ether
// For ethers v5
// const balance = ethers.utils.formatEther(
// await ethersProvider.getBalance(address) // Balance is in wei
// );
const balance = ethers.formatEther(
await provider.getBalance(account) // Balance is in wei
);
console.log(balance);
};
Sign Message
- Web3
- Ethers.js
const signMessage = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const web3 = new Web3(provider as any);
// Get user's Ethereum public address
const account = (await web3.eth.getAccounts())[0];
// Message
const message = "Hello MPC, Bye Bye SeedPhrase";
const typedMessage = [
{
type: "string",
name: "message",
value: message,
},
];
const params = [JSON.stringify(typedMessage), account];
const method = "eth_signTypedData";
const signedMessage = await this.provider.request({
method,
params,
});
console.log(signedMessage);
};
const signMessage = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const provider = new ethers.providers.Web3Provider(provider);
const signer = provider.getSigner();
const originalMessage = "Hello MPC, Bye Bye SeedPhrase";
const signedMessage = await signer.signMessage(originalMessage);
console.log(signedMessage);
};
Sign Transaction
const signTransaction = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const web3 = new Web3(provider as any);
const accounts = await web3.eth.getAccounts();
const txRes = await web3.eth.signTransaction({
from: accounts[0],
to: accounts[0],
value: web3.utils.toWei("0.0001"),
chainId: 1, // change it to your specific chain id.
});
console.log(txRes.transactionHash);
};
Send Transaction
- Web3
- Ethers.js
const sendTransaction = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const web3 = new Web3(provider as any);
const accounts = await web3.eth.getAccounts();
const txRes = await web3.eth.sendTransaction({
from: accounts[0],
to: accounts[0],
value: web3.utils.toWei("0.0001"),
chainId: 1, // change it to your specific chain id.
});
console.log(txRes.transactionHash);
};
const sendTransaction = async () => {
if (!provider) {
console.log("provider not initialized yet");
return;
}
const provider = new ethers.providers.Web3Provider(provider);
const signer = await provider.getSigner();
const address = signer.getAddress();
const tx = await signer.sendTransaction({
to: address,
value: ethers.utils.parseEther("0.0001"),
chainId: 1, // change it to your specific chain id.
});
const receipt = await tx.wait();
console.log(receipt.transactionHash);
};
Example code
Try our Demo Application with Web3Auth & Firebase integration. It works for either Ethereum, Solana or Polygon. The source code for the demo application is available here.
The code for the application we developed in this guide can be found in the Web3Auth Firebase Example. Check it out and try running it locally yourself!
Questions?
Ask us on Web3Auth's Community Portal