Skip to content

Instantly share code, notes, and snippets.

@yashovardhan
Last active June 14, 2022 08:10
Show Gist options
  • Save yashovardhan/643605aaf995fbb191275f333623b19a to your computer and use it in GitHub Desktop.
Save yashovardhan/643605aaf995fbb191275f333623b19a to your computer and use it in GitHub Desktop.

This guide will cover the basics of how to set up your Web3Auth SDK and Auth0 account for the integration and provide you with the links on how to develop a basic web application on the blockchain of your choice. Before starting, you can try the integration in our example here.

How it works?

To connect to a blockchain and make transactions, you need a private key or a wallet application like Metamask, Phantom etc. The Web3Auth SDK enables you to generate a private key for the user to work directly with your blockchain of choice, after the user has logged in with traditional login methods, like Google, Facebook, Twitter, etc. This is done by generating a private key in a self custodial way for the user shared across all applications linked to your Auth0 and Web3Auth accounts, via Web3Auth's MPC architecture. This enables users to have the same experience they are used to when logging in. Crypto native users can still connect with the wallet provider of their choice. Learn more about how the Web3Auth key infrastructure works here.

When integrating Web3Auth with Auth0 SPA the flow looks something like this:

For Auth0 RWA, we need an additional backend server to communicate with Auth0. The flow for RWA with Web3Auth looks something like this:

  • When a user logs in with 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 API Reference for more information.

  • Create an Auth0 tenant and configure a Single Page Web Application (SPA for Web) or Native (for Mobile) from Auth0 Console.

    • Please note that Regular Web Applications(RWA) are also supported, however for the guide here, we’re preferring SPA since its implicit flow doesn’t require an application to host a server. You can read more on using Web3 auth with an RWA in this documentation.
  • Create a Web3Auth account on the Web3Auth Dashboard

Setup

Setup your Auth0 Tenant

  • Add the following URLs for your app to the Allowed Web Origins field when configuring your Auth0 Application.
  • You will require domain and clientId of the newly created application which you can copy from Auth0 Console.

Setup your Web3Auth Dashboard

  • Enter your desired Project name

  • Select the blockchain(s) you'll be building this project on. For interoperability with Torus Wallet, you've an option of allowing the user's private key to be used in other applications using Torus Wallet. We currently have this option across EVM and Solana and Casper blockchains.

  • Finally, once you create the project, you've the option to whitelist your URLs for the project. Please whitelist the domains where your project will be hosted.

  • 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.
    • Select verifier type as Auth0
    • Choose your Authentication Type as the Auth Provider you've selected.
    • Paste the clientId and domain from the Auth0 SPA you create in the above steps. This will be used to validate the JWT token issued by Auth0.

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

Installation

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 using the Web3Auth Core SDK and the OpenLogin Provider to enable Custom Authentication through Auth0.


NOTE: Your base project will need to be setup to use Web3 libraries​

While working with Web3, there are certain packages that are not available in the browser environment that you will need to polyfill. Follow this documentation for how to get setup.


Install the following packages:

@web3auth/core

This is the Core package that contains the Web3Auth SDK.

npm install --save @web3auth/core

@web3auth/openlogin-adapter

For using Custom Authentication, we need to use the OpenLogin Adapter, where we can initialize 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

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 multi step process where we add all the config details for Web3Auth and OpenloginAdapter. Please make sure all of this is happening when the component mounts in your application using useEffect hook. This makes sure that Web3Auth is initialized when your application starts up.

Import packages

import { Web3AuthCore } from "@web3auth/core";
import { WALLET_ADAPTERS, CHAIN_NAMESPACES } from "@web3auth/base";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";

Alongside the Web3AuthCore and OpenloginAdapter you need the above mentioned packages from @web3auth/base for different initializations mentioned further in this guide.

Setup the Web3Auth SDK

import { Web3AuthCore } from "@web3auth/core";
import { CHAIN_NAMESPACES } from "@web3auth/base";

const web3auth = new Web3AuthCore({
  chainConfig: {
    chainNamespace: CHAIN_NAMESPACES.EIP155,
    chainId: "0x1",
  },
});

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.

Initialize the Openlogin Adapter

const openloginAdapter = new OpenloginAdapter({
  adapterSettings: {
    clientId: "YOUR-WEB3AUTH-CLIENT-ID",
    network: "testnet",
    uxMode: "popup",
    loginConfig: {
      jwt: {
        name: "Name of your choice",
        verifier: "YOUR-VERIFIER-NAME-ON-WEB3AUTH-DASHBOARD",
        typeOfLogin: "jwt",
        clientId: "YOUR-CLIENTID-ON-AUTH0-DASHBOARD",
      },
    },
  },
});

web3auth.configureAdapter(openloginAdapter);

Here, you need to pass over your Web3Auth clientId in the adapterSettings object and your Custom Auth verifierName and Auth0 clientId in the loginConfig object. This makes sure that the Openlogin Adapter can connect to the correct verifier and Auth0 server.

Initialize the Web3Auth SDK

Initializing the Web3

await web3auth.init();

Authentication

Login

Once initialized, you can use the connectTo() function to authenticate the user when they click the login button.

import { WALLET_ADAPTERS, CHAIN_NAMESPACES } from "@web3auth/base";

await web3auth.connectTo(WALLET_ADAPTERS.OPENLOGIN, {
  relogin: true,
  loginProvider: "jwt",
  extraLoginOptions: {
    domain: "https://YOUR-AUTH0-DOMAIN", // Please append "https://" before your domain
    verifierIdField: "sub",
  },
});

When connecting, your connectTo function takes the arguments for the adapter you want to connect to and the options for the login. The major thing to note here is the domain option in the extraLoginOptions object. This is the domain of your Auth0 tenant so that you can be redirected to login there directly from the Web3Auth Core 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 JWT token you received from Auth0 and lives in the frontend context.

Logout

await web3auth.logout();

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

Interacting with the 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, using the function, web3auth.provider.request({method: "private_key"}) from the Web3Auth provider. Hence application can have access to the user's app scoped private key and make RPC calls

  • 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.
  • 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

Try our Demo Application and Example Code

Try our Demo Application with Web3Auth & Auth0 integration. It works for either Ethereum, Solana or Polygon. It also works for both the flows, ie. SPA and RWA. The code for the Demo application can also be found in the Web3Auth Auth0 Example. Check it out and try running it locally yourself!

For the application we've built in this example, refer to this code below:

Finally, if you want to view the code for the application we developed above, checkout our documentation which has it covered for you.

Web3Auth Quick Starts

Still looking for a quick way to get started?

Follow the steps for setting up above and try one of our quick-starts for your respective framework.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment