Skip to main content

How to use Auth0 with Web3Auth Flutter SDK

pnpflutterandroidiosauth0custom authenticationevmWeb3Auth Team | January 17, 2023

This guide will cover the basics of how to use the Web3Auth Flutter SDK in your Flutter application with Auth0 and make blockchain calls to get access to user's account, fetch balance, sign transaction, and send transaction.

Repository: https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/flutter/flutter-auth0-example

Quick Start

npx degit Web3Auth/web3auth-pnp-examples/flutter/flutter-auth0-example w3a-flutter-auth0-demo
cd w3a-flutter-auth0-demo
# Open in Android Studio or VS Code
flutter run

How it works?

When integrating Web3Auth Flutter SDK with Social Login the flow looks something like this:

Web3Auth Core - Social Login Flow

  • When a user logs in with Google via Auth0. Auth0 sends a JWT id_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

  • Android API version 24 or newer.
  • For Android build: compileSdkVersion needs to be 34. Check android/app/build.gradle in your Flutter project to change it.
  • iOS 12+
  • Xcode 11.4+ / 12.x
  • Swift 4.x / 5.x
  • For iOS build: platform :ios needs to be 13.0. Check ios/Podfile in your Flutter project to change it.
  • Create an Auth0 tenant and configure a Single Page Web Application (SPA for Web) or Native (for Mobile) from Auth0 Console.

Setup your Auth0 Tenant

  • Add the following URLs for your app to the Allowed Web Origins field when configuring your Auth0 Application.

    Add Callback URL to Auth0 Dashboard

  • You will require domain and clientId of the newly created application which you can copy from Auth0 Console. Domain and Client ID from Auth0 Dashboard

Enable Social login

Enable SMS Passwordless

Optional

If you want to implement SMS Passwordless, then this section is for you. Else you can skip this.

  • Enable SMS on the Authentication > Passwordless page of your Auth0 Dashboard. Auth0 Dashboard to enable SMS Passwordless Option
  • Under Settings tab, add your Twilio SID and Twilio AuthToken. Auth0 Dashboard to enable SMS Passwordless | Setup
  • Also, update the From number on the same page, and click on the Save button.
  • Next, enable your application under Applications tab, and click on the Save button. Auth0 Dashboard to enable SMS Passwordless | Enable App
  • You can test sending a SMS from the Try tab. Once, a SMS comes with OTP, it means it has been successfully configured.
Update Lockscreen for SMS Passwordless
update-lock-screen

If you're to use SMS Passwordless, please visit here to setup the Lock Screen of Auth0 from your Auth0 Dashboard.

Enable Email Passwordless

Optional

If you want to implement Email Passwordless, then this section is for you. Else you can skip this.

  • Enable Email on the Authentication > Passwordless page of your Auth0 Dashboard. Auth0 Dashboard to enable Email Passwordless Option
  • Under Settings tab, update From and Subject based on your need and click on the Save button. Auth0 Dashboard to enable Email Passwordless | Setup
  • Next, enable your application under Applications tab, and click on the Save button. Auth0 Dashboard to enable Email Passwordless | Enable App
  • You can test sending an Email from the Try tab. Once, an Email comes with OTP/Link, it means it has been successfully configured.
Update Lockscreen for Email Passwordless
update-lock-screen

If you're to use Email Passwordless, please visit here to setup the Lock Screen of Auth0 from your Auth0 Dashboard.

Setup your Web3Auth Dashboard

  • Create a Project from the Project Section of the Web3Auth Developer Dashboard.

    Plug n Play Project Creation on Web3Auth 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 Flutter as the platform.

    • Select the Web3Auth Network as Sapphire Devnet. We recommend creating a project in the Sapphire Devnet network during development. While moving to a production environment, make sure to convert your project to Sapphire Mainnet or any of the legacy mainnet network Mainet, Aqua, or Cyan 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.

      Plug n Play Project - Whitelist

  • Add {SCHEME}://{YOUR_APP_PACKAGE_NAME} (e.g, w3a://com.example.w3aflutter) for Android and {bundleId}://auth (e.g, com.example.w3aflutter://openlogin) for iOS in the Whitelist URL field of the Web3Auth Dashboard.

Create Social Verifiers

  • Create a Verifier from the Custom Auth Section of the Developer Dashboard with the following configuration:

    • Choose a name of your choice for the verifier identifier. eg. auth0-project

    • Select Auth0 from the Login Provider.

    • Choose your Authentication Type from eg. Google, Twitter, GitHub etc.. to be the Auth provider.

    • Paste the Client ID and Auth0 Domain from the Auth0 SPA you created in the above steps. This will be used to validate the JWT token issued by Auth0.

    • Click on Create button to create your verifier. It may take up to 10-20 minutes to deploy verifier on testnet. You'll receive an email once it's complete.

      Create Social Verifier

    You will require the verifierName of the newly created verifier and clientId of the Plug and Play Project.

Create SMS Passwordless Verifier

Optional

If you want to implement SMS Passwordless, then this section is for you. Else you can skip this.

  • Create a Verifier from the Custom Auth Section of the Developer Dashboard with the following configuration:

    • Choose a name of your choice for the verifier identifier. eg. auth0-sms-passwordless

    • Select Custom from the Login Provider.

    • Choose Custom for the JWT Verifier ID and type name.

    • Enter https://{YOUR-DOMAIN}.auth0.com/.well-known/jwks.json as your JWKS Endpoint. This will be used to validate the JWT token issued by Auth0.

    • JWT validation fields:

      • iss: https://{YOUR-DOMAIN}.auth0.com
      • aud: {AUTH0-CLIENT-ID}
    • Click on Create button to create your verifier. It may take up to 10-20 minutes to deploy verifier on testnet. You'll receive an email once it's complete.

      Create SMS Passwordless Verifier

    You will require the verifierName of the newly created verifier and clientId of the Plug and Play Project.

Create Email Passwordless Verifier

Optional

If you want to implement Email Passwordless, then this section is for you. Else you can skip this.

  • Create a Verifier from the Custom Auth Section of the Developer Dashboard with the following configuration:

    • Choose a name of your choice for the verifier identifier. eg. auth0-email-passwordless

    • Select Auth0 from the Login Provider.

    • Choose your Authentication Type as Passwordless to use Auth0's Email Passwordless.

    • Paste the Client ID and Auth0 Domain from the Auth0 SPA you created in the above steps. This will be used to validate the JWT token issued by Auth0.

    • Click on Create button to create your verifier. It may take up to 10-20 minutes to deploy verifier on testnet. You'll receive an email once it's complete.

      Create Email Passwordless Verifier

    You will require the verifierName of the newly created verifier and clientId of the Plug and Play Project.

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 using the Web3Auth Flutter SDK.

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 as a dependency to your pubspec.yaml.

dependencies:
web3auth_flutter: ^5.0.4

Add web3auth_flutter using flutter pub add command.

flutter pub add web3auth_flutter

Update compileSdkVersion

For Android build compileSdkVersion needs to be 34. Check your app module gradle file in your project to change it.

android {
namespace "com.example.app_name"
compileSdkVersion 34
// ..
}

Add Web3Auth to Gradle

In your project-level gradle file add JitPack repository.

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url "https://jitpack.io" } // <-- Add this line
}
}

Permissions

Open your app's AndroidManifest.xml file and add the following permission. Please make sure the <uses-permission> element should be a direct child of the <manifest> root element.

<uses-permission android:name="android.permission.INTERNET" />

Configuration

Once the gradles and permission has been updated, we need to configure Web3Auth project by whitelisting you scheme and package name.

Configure a Plug n Play project
  • Go to Web3Auth Developer Dashboard, and create or open an existing Web3Auth project.
  • Whitelist {SCHEME}://{YOUR_APP_PACKAGE_NAME} in the developer dashboard. This step is mandatory for the redirect to work.

Open your app's AndroidManifest.xml file and add the following deep link intent filter to your Main activity

<intent-filter>
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:scheme="{scheme}" android:host="{YOUR_APP_PACKAGE_NAME}" android:path="/path" />
<!-- Accept URIs: w3a://com.example.w3aflutter -->
</intent-filter>

Initialization

After Installation, the next step to use Web3Auth is to Initialize the SDK. This can be achieved by using the init() function.

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.

Create Web3Auth Instance

In your main.dart file, initialize the Web3AuthFlutter plugin at the very beginning such as in the overriden initState function

import 'dart:collection';
import 'dart:io';
import 'dart:async';

import 'package:web3auth_flutter/web3auth_flutter.dart';
import 'package:web3auth_flutter/enums.dart';
import 'package:web3auth_flutter/input.dart';
import 'package:web3auth_flutter/output.dart';


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

// Initialization
Future<void> initPlatformState() async {

Uri redirectUrl;
if (Platform.isAndroid) {
redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
// w3a://com.example.w3aflutter/auth
} else if (Platform.isIOS) {
redirectUrl = Uri.parse('{bundleId}://auth');
// com.example.w3aflutter://openlogin
} 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: "Web3Auth Flutter Auth0 Example",
clientId: "AUTH0-CLIENT-ID" // auth0 client id
);

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

await Web3AuthFlutter.initialize();
}

Read more about initializing the Flutter SDK here.

Authentication

Logging in

Once initialized, you can use the Web3AuthFlutter.login(LoginParams( loginProvider: Provider.google )) function to authenticate the user when they click the login button.

VoidCallback _login(Future<Web3AuthResponse> Function() method) {
return () async {
try {
final Web3AuthResponse response = await method();
setState(() {
_result = response.toString();
logoutVisible = true;
});
} on UserCancelledException {
print("User cancelled.");
} on UnKnownException {
print("Unknown exception occurred");
}
};
}

Future<Web3AuthResponse> _withAuth0() {
return Web3AuthFlutter.login(LoginParams(
loginProvider: Provider.jwt,
mfaLevel: MFALevel.OPTIONAL,
extraLoginOptions: ExtraLoginOptions(
domain: 'YOUR_AUTH0_DOMAIN', // eg. https://torus.us.auth0.com
verifierIdField: 'sub')));
}

When connecting, the login function takes the LoginParams arguments for the login. See the LoginParams for more details.

Sample loginResponse

{
"privKey": "0ajjsdsd....",
"userInfo": {
"email": "w3a-heroes@web3auth.com",
"name": "Web3Auth Heroes",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"verifier": "torus",
"verifierId": "w3a-heroes@web3auth.com",
"typeOfLogin": "google",
"aggregateVerifier": "w3a-google-sapphire",
"dappShare": "", // 24 words of 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
"isMfaEnabled": false // Returns whether the user has enabled MFA or not
},
"ed25519PrivKey": "666523652352635....",
"coreKitKey": "0xajjsdsd....",
"coreKitEd25519PrivKey": "666523652352635....",
"sessionId": "0xajjsdsd...."
}

Get the User Profile

// Assuming the user is logged in, get the user profile from the web3AuthResponse
userInfo = web3AuthResponse.userInfo

Using the web3AuthFlutter.login function, you can get the details of the logged in user. Please note that these details are not stored anywhere in Web3Auth network.

If you wish you add Multi Factor Authentication, use dApp Share

Logout

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

Logging out your user is as simple as calling the web3AuthFlutter.logout() function.

UI in this guide


Widget build(BuildContext context) {
// Map<String, dynamic> user = jsonDecode(_result);

return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Web3Auth x Flutter Example'),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Padding(
padding: EdgeInsets.all(8.0),
),
Visibility(
visible: !logoutVisible,
child: Column(
children: [
const Icon(
Icons.flutter_dash,
size: 80,
color: Color(0xFF1389fd),
),
const SizedBox(
height: 40,
),
const Text(
'Web3Auth',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 36,
color: Color(0xFF0364ff)),
),
const SizedBox(
height: 10,
),
const Text(
'Welcome to Web3Auth x Flutter Auth0 Demo',
style: TextStyle(fontSize: 14),
),
const SizedBox(
height: 20,
),
const Text(
'Login with',
style: TextStyle(fontSize: 12),
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: _login(_withAuth0),
child: const Text('Auth0')),
],
),
),
Visibility(
// ignore: sort_child_properties_last
child: Column(
children: [
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor:
Colors.red[600] // This is what you need!
),
onPressed: _logout(),
child: Column(
children: const [
Text('Logout'),
],
)),
),
],
),
visible: logoutVisible,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(_result),
)
],
)),
),
),
);
}

Interacting with the Blockchain

Blockchain calls

Check out the full codes to interact with ETH Blockchain.

Get Account

import 'package:web3dart/web3dart.dart';
import 'package:shared_preferences/shared_preferences.dart';

// checkout the Connect Blockchain > Ethereum > Flutter to get full code.


Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
// Get Account
ElevatedButton(
onPressed: () async {
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
debugPrint("Account, ${address.hexEip55}");
},
child: const Text('Get Address'),
),
])));
}

Get Balance

import 'package:web3dart/web3dart.dart';
import 'package:shared_preferences/shared_preferences.dart';

// checkout the Connect Blockchain > Ethereum > Flutter to get full code.


Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
// Get Balance
ElevatedButton(
onPressed: () async {
final prefs = await SharedPreferences.getInstance();
final privateKey = prefs.getString('privateKey') ?? '0';
final credentials = EthPrivateKey.fromHex(privateKey);
final client = Web3Client(rpcUrl, Client());
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
final balance = await client.getBalance(address);
debugPrint("Balance, ${balance}");
},
child: const Text('Get Balance'),
),
])));
}

Send Transaction

import 'package:web3dart/web3dart.dart';
import 'package:shared_preferences/shared_preferences.dart';

// checkout the Connect Blockchain > Ethereum > Flutter to get full code.


Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
// Send Transaction
ElevatedButton(
onPressed: () async {
final prefs = await SharedPreferences.getInstance();
final privateKey = prefs.getString('privateKey') ?? '0';
final client = Web3Client(rpcUrl, Client());
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
final receipt = await client.sendTransaction(
credentials,
Transaction(
from: address,
to: EthereumAddress.fromHex(
'0x809D4310d578649D8539e718030EE11e603Ee8f3'),
value: EtherAmount.fromUnitAndValue(
EtherUnit.gwei, 5000000), // 0.005 ETH
),
chainId: 5); // change chainId as per your chain.
debugPrint("Receipt, ${receipt}");
},
child: const Text('Send Transaction'),
),
])));
}

Example code

The code for the application we developed in this guide can be found in the Web3Auth Flutter Auth0 Example. Check it out and try running it locally yourself!

flutter run

Also, check other examples:

Questions?

Ask us on Web3Auth's Community Support Portal