Skip to main content

How to integrate Firebase with Web3Auth Flutter SDK

pnpflutterandroidios firebasecustom authenticationevmWeb3Auth Team | January 17, 2023

In this guide, we'll talk about how we can use Web3Auth Flutter SDK with Firebase in your Flutter application.

As an overview, the guide is quite simple, with functionality to log in, display user details, and perform blockchain interactions. The signing of the blockchain transactions is done through the Web3Auth embedded wallet. You can check out the infrastructure docs, "Web3Auth Wallet Management Infrastructure" for a high-level overview of the Web3Auth architecture and implementation. For those who want to skip straight to the code, you can find it on GitHub.

How to set up Web3Auth Dashboard

If you haven't already, sign up on the Web3Auth platform. It is free and gives you access to the Web3Auth's base plan. After the basic setup, explore other features and functionalities offered by the Web3Auth Dashboard. It includes custom verifiers, whitelabeling, analytics, and more. Head to Web3Auth's documentation page for detailed instructions on setting up the Web3Auth Dashboard.

How to set up Firebase for Flutter

If you haven't already setup the Firebase for your Flutter app, please setup the Firebase, as it's the prerequisites for the guide. Head to the Firebase's documentation for the details instructions.

How to set up Custom Verifer

Once, you have set up the Web3Auth Dashboard, created a new project, and set up Firebase, it's time to create a Custom Verifier for your Firebase application. We already have detail instructions on how to create a Custom Verifier for Firebase, please head to our documentation.

Integrating Web3Auth SDK in Flutter

Once, you have set up the Custom Verifier, it's time to integrate Web3Auth in your Flutter application. For the implementation, we'll use the web3auth_flutter. This SDK facilitates integration with Web3Auth, and allows you to easily manage embedded wallet in your Flutter application.

Installation

To install the web3auth_flutter package, you have two options. You can either manually add the package in the pubspec.yaml file, or you can use the flutter pub add command.

Add web3auth_flutter using flutter pub add command.

flutter pub add web3auth_flutter

Initialization

After successfully installing the package, the next step is to initialize Web3Auth in your Flutter app. This sets up the necessary configurations using Client Id and prepares Web3Auth. Learn more about Web3Auth Initialization.

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 customise your Web3Auth Instance.

import 'package:web3auth_flutter/web3auth_flutter.dart';


void initState() {
super.initState();
initPlatformState();
}

Future<void> initPlatformState() async {
final Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
} else {
throw UnKnownException('Unknown platform');
}

final loginConfig = HashMap<String, LoginConfigItem>();

loginConfig['jwt'] = LoginConfigItem(
verifier: "VERIFIER_NAME", // get it from web3auth dashboard
typeOfLogin: TypeOfLogin.jwt,
name: "Firebase JWT Login",
clientId: "WEB3AUTH_CLIENT_ID", // web3auth's plug and play client id
);

await Web3AuthFlutter.init(
Web3AuthOptions(
clientId:'YOUR WEB3AUTH CLIENT ID FROM DASHBOARD',
network: Network.cyan,
redirectUri: redirectUrl,
loginConfig: loginConfig,
)
);

await Web3AuthFlutter.initialize();
}

Authentication

If the user is not authenticated, you should utilize the login method. For the example, we'll use the Firebase signInWithEmailAndPassword method to authorize user, and retrive the JWT token. This token, then can be used as input for Web3Auth login. We'll create a helper function _withJWT method. The login method is pretty straightforward, it authorizes user using Firebase, and uses the Firebase id token to login in Web3Auth. To pass the JWT token from the Firebase, we'll use ExtraLoginOptions.

Learn more about Web3Auth LoginParams.

Future<Web3AuthResponse> _withJWT() async {
String idToken = "";
try {
final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: 'custom+id_token@firebase.login',
password: 'Welcome@W3A',
);

idToken = await credential.user?.getIdToken(true) ?? '';
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
log('No user found for that email.');
} else if (e.code == 'wrong-password') {
log('Wrong password provided for that user.');
}
}

return Web3AuthFlutter.login(
LoginParams(
loginProvider: Provider.jwt,
extraLoginOptions: ExtraLoginOptions(
id_token: idToken,
domain: 'firebase',
),
),
);
}

Logout

To logout the existing user, we'll simply use the logout method of Web3AuthFlutter.

VoidCallback _logout() {
return () async {
try {
await Web3AuthFlutter.logout();
setState(() {
_result = '<empty>';
logoutVisible = false;
});
} on UserCancelledException {
print("User cancelled.");
} on UnKnownException {
print("Unknown exception occurred");
}
};
}

Set up Blockchain Providers

Once we have successfully authenticated the user, the next step would be to fetch the user details, retrieve wallet address and prepare blockchain providers for interactions. For this guide, we are supporting only Ethereum ecosystem, but the general idea can be used for any blockchain ecosystem.

For interacting with ethereum chains, we'll use the web3dart SDK. To install the web3dart package, you have two options. You can either manually add the package in the pubspec.yaml file, or you can use the flutter pub add command.

Add web3dart using flutter pub add command.

flutter pub add web3dart

After successfully installing package, it's time to create Credentials instance to retrive user's EOA address, and sign the transactions. To retrive the user's private key, we'll use the getPrivateKey method.

final privateKey = await Web3AuthFlutter.getPrivKey();
final Credentials credentials = EthPrivateKey.fromHex(privateKey);

// User's EOA address
log(credentials.address)

To retrive user's balance, and interacting with Blockcahin, you can follow our detailed guide on how to interact with EVM chain guides. Since, you already have created Credentials instance, and retrived the user's EOA address, you can skip that part. To interact with Solana blockchain, you can checkout our Solana blockchain guide.

Conclusion

Voila, you have learned how to use Firebase with Web3Auth PnP SDK with Flutter application.

If you are interested in learning more about PnP SDK, please checkout our documentation for Flutter PnP SDK. You can find the code used for the guide on our examples repo.