Integrate Firebase with Web3Auth Plug and Play No Modal SDK
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/single-verifier-examples/firebase-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 a Federated Identity Provider.
-
A Google Developer account to be used as an Identity provider for Firebase.
Setup
Setup Firebase
- Go to your Firebase console and create a Web App. Follow this guide on how to set up 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 the Sign-in method tab, select any provider you wish to enable. For 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 the Register button to register the app for Web.
-
The 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
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 the 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, we will be talking through the Web3Auth Plug and Play No Modal SDK and using the Auth Adapter 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/auth-adapter @web3auth/ethereum-provider @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/auth-adapter
For using Custom Authentication, we need to use the Auth Adapter, where we can initialize the authentication details.
npm install --save @web3auth/auth-adapter
@web3auth/ethereum-provider
For using the EVM compatible blockchains, we need to use the Ethereum Provider package, which will be used to connect to the blockchain.
npm install --save @web3auth/ethereum-provider
@web3auth/base
Since we're using typescript, we need the @web3auth/base
package to provide the 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 initialized when your application starts up.
For this guide, we're only focusing on the Instantiation, Configuration for the Auth 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, check out our SDK Reference.
Instantiating Web3Auth
Importing the packages
import { WALLET_ADAPTERS, CHAIN_NAMESPACES, IProvider } from "@web3auth/base";
import { Web3AuthNoModal } from "@web3auth/no-modal";
import { AuthAdapter } from "@web3auth/auth-adapter";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
Alongside the Web3Auth
and AuthAdapter
you need the above-mentioned packages from
@web3auth/base
for different initializations 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",
blockExplorerUrl: "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 because 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.
Initializing the Auth Adapter
const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });
const authAdapter = new AuthAdapter({
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(authAdapter);
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 Auth Adapter can connect to
the correct verifier and Firebase server.
Initializing the Web3Auth SDK
await web3auth.init();
Initializing 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 log in 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.AUTH, {
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;
}
// For ethers v5
// const ethersProvider = new ethers.providers.Web3Provider(this.provider);
const ethersProvider = new ethers.BrowserProvider(this.provider);
// For ethers v5
// const signer = ethersProvider.getSigner();
const signer = await ethersProvider.getSigner();
// Get the user's Ethereum public address
const address = signer.getAddress();
console.log(address);
};
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;
}
// For ethers v5
// const ethersProvider = new ethers.providers.Web3Provider(this.provider);
const ethersProvider = new ethers.BrowserProvider(this.provider);
// For ethers v5
// const signer = ethersProvider.getSigner();
const signer = await ethersProvider.getSigner();
// Get the user's Ethereum public address
const address = signer.getAddress();
// Get the 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 ethersProvider.getBalance(address), // 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;
}
// For ethers v5
// const ethersProvider = new ethers.providers.Web3Provider(this.provider);
const ethersProvider = new ethers.BrowserProvider(this.provider);
// For ethers v5
// const signer = ethersProvider.getSigner();
const signer = await ethersProvider.getSigner();
const originalMessage = "YOUR_MESSAGE";
// Sign the message
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;
}
// For ethers v5
// const ethersProvider = new ethers.providers.Web3Provider(this.provider);
const ethersProvider = new ethers.BrowserProvider(this.provider);
// For ethers v5
// const signer = ethersProvider.getSigner();
const signer = await ethersProvider.getSigner();
const destination = "0x40e1c367Eca34250cAF1bc8330E9EddfD403fC56";
// Convert 1 ether to wei
// For ethers v5
// const amount = ethers.utils.parseEther("0.001");
const amount = ethers.parseEther("0.001");
// Submit transaction to the blockchain
const tx = await signer.sendTransaction({
to: destination,
value: amount,
maxPriorityFeePerGas: "5000000000", // Max priority fee per gas
maxFeePerGas: "6000000000000", // Max fee per gas
});
// Wait for the transaction to be mined
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 Support Portal