Integrate Firebase with Web3Auth React Native SDK
This guide will cover the basics of how to use the Web3Auth React Native SDK in your React Native application.
Repository: https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/react-native/rn-bare-firebase-example
Quick Start
npx degit Web3Auth/web3auth-pnp-examples/react-native/rn-bare-firebase-example w3a-rn-bare-firebase-demo && cd w3a-rn-bare-firebase-demo && npm install
# For Android
npm run android
# For iOS
cd ios && pod install && cd .. && npm run ios
How it works?
When integrating Web3Auth React Native SDK with Firebase the 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
-
React Native Release 0.71 and above (for Bare React Native Workflow)
-
iOS Platform Target Version 14 and above
-
Android Target SDK Version 31 and above
-
A Firebase account to be used as Federated Identity Provider.
-
A Google Developer account to be used as Identity provider for Firebase.
Setup
Setup your Firebase Project
- 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 Android
-
Once the project is created and authentication is configured. Let's use Firebase for Android by clicking on the
Android
button on the home screen of your project. -
In the next screen, enter the Android package name and click on Register app button to register the app for Android.
-
In the Next screen, Download and add config file to your Android Studio Project as shown below. Then Click on
Next
button. -
Next screen shows ways to add Firebase to your application. To make the
google-services.json
config values accessible to Firebase SDKs, you need the Google services Gradle plugin. We will be adding the buildscript dependency to the<project>/build.gradle
file. -
Then, in your module (app-level)
build.gradle
file, add both the google-services plugin and any Firebase SDKs that you want to use in your app: -
After adding the plugin and the desired SDKs, sync your Android project with Gradle files.
Setup your Web3Auth Dashboard
-
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.
-
Create Firebase Verifier on Web3Auth Dashboard
-
Create a Verifier from the Custom Auth Section of the Web3Auth Developer Dashboard with following configuration:
- Choose a name of your choice for the verifier identifier.
eg. w3a-firebase-verifier
- Select environment:
testnet
,mainnet
,aqua
, orcyan
as per your requirement. - Select
Custom
from the Login Provider. - Select
Sub
for the JWT Verifier ID. - Enter
https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com
as the JWK endpoint for Firebase's idToken. - JWT validation fields:
- iss:
https://securetoken.google.com/<firebase-project-id>
. - aud:
<firebase-project-id>
- iss:
- Click on
Create
button to create your verifier. It may take up to 10 minutes to deploy verifier on testnet. You'll receive an email once it's complete.
- Choose a name of your choice for the verifier identifier.
-
You will require the
verifierName
of the newly created verifier andclientId
of the Plug and Play Project.
- Add
{YOUR_APP_SCHEME}://auth
in the Whitelist URL field of the Web3Auth Dashboard.
Configure Deep Link
- Android
- iOS
- Make sure that the minimum SDK compile version in
build.gradle
is 31 or more.
buildToolsVersion = "31.0.0"
minSdkVersion = 21
compileSdkVersion = 31
targetSdkVersion = 31
- Add the intent filter with the
scheme
defined in yourAndroidManifest.xml
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
# replace with your own scheme
<data android:scheme="web3authrnexample" />
</intent-filter>
- SDK version 31 requires you to explicitly define
android:exported="true"
inAndroidManifest.xml
, and check whether it is correctly present or not.
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
- Your
redirectUrl
is your defined scheme following some identifier or your choice. For example, if your scheme isweb3authrnexample
, you can define yourredirectUrl
asweb3authrnexample://openlogin
. Make sure you register thisredirectUrl
in the Web3Auth Developer Dashboard.
const scheme = "web3authrnbareexample"; // Or your desired app redirection scheme
const resolvedRedirectUrl = `${scheme}://openlogin`;
const scheme = "web3authrnbareexample"; // Or your desired app redirection scheme
const resolvedRedirectUrl = `${scheme}://openlogin`;
- Make sure that the minimum SDK compile version in
Podfile
is 14 or more.
platform :ios, '14'
- Install the Cocoa Pods within your project directory.
cd ios && pod install && cd ..
- In iOS, you don't need to add
redirectUrl
as an iOS Custom URL Scheme, however, you may add it to yourInfo.plist
, but it is not required. Make sure yourredirectUrl
is registered in the Web3Auth Developer Dashboard.
Using the Web3Auth SDK
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 React Native SDK.
Installation
@web3auth/react-native-sdk
- npm
- Yarn
- pnpm
npm install --save @web3auth/react-native-sdk
yarn add @web3auth/react-native-sdk
pnpm add @web3auth/react-native-sdk
Adding a Web Browser Module
We will also require a WebBrowser
implementation to allow our JS-based SDK to interact with the
native APIs, and different extra installation steps depending on whether you are using the bare
workflow or managed workflow. Since we're using the SDK with a bare workflow React Native app, you
have to install a WebBrowser
implementation made by us as a port from the Expo Web Browser Module.
@toruslabs/react-native-web-browser
- npm
- Yarn
- pnpm
npm install --save @toruslabs/react-native-web-browser
yarn add @toruslabs/react-native-web-browser
pnpm add @toruslabs/react-native-web-browser
Adding an EncryptedStorage
Module
We will also require an EncryptedStorage
implementation to allow for session management without
storing the private key on the device.
- npm
- Yarn
- pnpm
npm install --save react-native-encrypted-storage
yarn add react-native-encrypted-storage
pnpm add react-native-encrypted-storage
Initialization
After Installation, the next step to use Web3Auth is to Initialize the SDK. The Initialization is a two-step process,
Please note that these are the most critical steps where you need to pass on different parameters according to the preference of your project. Additionally, Whitelabeling and Custom Authentication have to be configured within this step, if you wish to customize your Web3Auth Instance.
Importing Web3Auth
You may also import additional types from the SDK to help in the development process.
import Web3Auth, { LOGIN_PROVIDER, OPENLOGIN_NETWORK } from "@web3auth/react-native-sdk";
Importing a WebBrowser
implementation
import * as WebBrowser from "@toruslabs/react-native-web-browser";
Importing a EncryptedStorage
implementation
import EncryptedStorage from "react-native-encrypted-storage";
Instantiating Web3Auth
It's time to create an instance of Web3Auth in the project.
We need clientId
and target Web3Auth network
to initialize the web3auth
object.
-
You can get your
clientId
from registering (above) on the Developer Dashboard. -
network
signifies the network on which the deployed Web3Auth nodes are running. For testing purposes, we have aSapphire Devnet
network. For production usage, you can use theSapphire Mainnet
network.
const web3auth = new Web3Auth(WebBrowser, EncryptedStorage, {
clientId,
network: OPENLOGIN_NETWORK.SAPPHIRE_MAINNET, // SAPPHIRE_MAINNET or SAPPHIRE_DEVNET
loginConfig: {
// Add login configs corresponding to the provider
// For firebase/ cognito & other providers, you need to pass the JWT token
// JWT login
jwt: {
verifier: "YOUR_JWT_VERIFIER_NAME", // Please create a verifier on the developer dashboard and pass the name here
typeOfLogin: "jwt",
},
// Add other login providers here
},
});
Authentication
Logging in with Firebase
We're using the React Native Firebase Library for this project. You can follow the official RNFirebase documentation to setup Firebase in your project.
import auth from "@react-native-firebase/auth";
import { GoogleSignin } from "@react-native-google-signin/google-signin";
async function signInWithFirebase() {
try {
GoogleSignin.configure({
webClientId: "461819774167-5iv443bdf5a6pnr2drt4tubaph270obl.apps.googleusercontent.com",
});
// Check if your device supports Google Play
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
// Get the user's ID token
const { idToken } = await GoogleSignin.signIn();
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
const res = await auth().signInWithCredential(googleCredential);
return res;
} catch (error) {
console.error(error);
}
}
Logging in with Web3Auth
Once initialized, you can use the login
function of web3auth
to navigate the user to the login
process. For each login method, you have to select the loginProvider
such as google
, facebook
,
twitch
, jwt
, email_passwordless
etc.
If you are using custom authentication through Firebase or Custom JWT, you have to use the JWT
login provider.
Additionally, in extraLoginOptions
you have to provide the details required by that specific
method as mentioned here.
Once a user logs in, the user can access the key by web3auth.privKey()
. For EVM Blockchains, the
secp256k1
private key is used to sign transactions. We can get an ed25519
compatible private key
for other blockchains using web3auth.ed25519Key()
.
const loginRes = await signInWithFirebase();
const idToken = await loginRes.user.getIdToken(true);
await web3auth.login({
redirectUrl: resolvedRedirectUrl,
mfaLevel: "default", // Pass on the MFA level of your choice: default, optional, mandatory, none
loginProvider: "jwt",
extraLoginOptions: {
id_token: "YOUR_JWT_ID_TOKEN", // Please replace with your JWT ID token, generated from Firebase Login
verifierIdField: "sub", // same as your JWT Verifier ID on the dashboard
},
});
If you wish you add Multi Factor Authentication, use dApp Share
Get the User Profile
// Assuming the user is logged in, get the user profile from the web3auth object
var userInfo = web3auth.userInfo();
Using the web3Auth.login()
function, you can get the details of the logged-in user. Please note
that these details are not stored anywhere in Web3Auth network.
Sample userInfo
{
"aggregateVerifier": "tkey-google",
"email": "john@gmail.com",
"name": "John Dash",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"typeOfLogin": "google",
"verifier": "torus",
"verifierId": "john@gmail.com",
"dappShare": "<24 words seed phrase>", // will be sent only incase of custom verifiers
"idToken": "<jwtToken issued by Web3Auth>",
"oAuthIdToken": "<jwtToken issued by OAuth Provider>", // will be sent only incase of custom verifiers
"oAuthAccessToken": "<accessToken issued by OAuth Provider>" // will be sent only incase of custom verifiers
}
Logout
Use the logout
function of web3auth
to log the user out.
web3auth.logout();
Interacting with the Blockchain
Once a user logs in, the user can access the private key by web3auth.privKey()
. For EVM
Blockchains, the secp256k1
private key is used to sign transactions. We can get an ed25519
compatible private key for other blockchains using web3auth.ed25519Key()
. Similar to how we're
using this private key in the ethers.js
library in this example, you can connect to any other
blockchain of your choice.
Please go through the Connect Blockchain Documentation, which contains all the details of the EVM-based blockchain you have selected here.
Troubleshooting React Native issues
Some commonly faced issues and the ways to fix them are addressed in this troubleshooting guide.
Example code
The code for the application we developed in this guide can be found in the Web3Auth React Native Example. Check it out and try running it locally yourself!
Questions?
Ask us on Web3Auth's Community Support Portal