Usage of Single Factor Auth JS SDK
Once you've installed and successfully initialized Web3Auth, you can use it to authenticate your users. Further, you can use the native provider given by Web3Auth to connect the users to the respective blockchain network.
Natively, the instance of Web3Auth (called web3auth in our examples) returns the following functions:
connect()
- Logs in the User using theverifier
,verifierId
&idToken
, which are mandatory, whilesubVerifierInfoArray
andserverTimeOffset
are optional.provider()
- Returns the native provider that can be used to make different blockchain transactions.sessionId()
- Returns the sessionId of the user as a string.authenticateUser()
- Returns a promise of theUserAuthInfo
object containing theidToken
of the user.addChain()
- Add chain configuration to the web3auth instance.switchChain()
- Switches the chainId to one of the added chainIds.getUserInfo()
- Returns the user information.logout()
- Log out the user from the web3auth instance.
Logging in your User
connect(loginParams: LoginParams)
To log a user in the Web3Auth SFA JS SDK, you need to call the connect()
function.
Variable | Description |
---|---|
loginParams | Mandatory login Parameters |
Returns
connect(loginParams: LoginParams): Promise<IProvider | null>
LoginParams
connect(loginParams: LoginParams)
On successful login, the connect()
function returns a IProvider
instance. This instance contains
the corresponding provider for your selected blockchain. You can use this provider to connect your
user to the blockchain and perform transactions.
On unsuccessful login, this function will return a null
value.
LoginParams
- Table
- Type Declarations
Parameter | Description |
---|---|
verifier | Details of the verifier. It's a mandatory parameter as a string. |
verifierId | Verifier ID's value, sub or email value present in the idToken. It's a mandatory parameter as a string. |
idToken | A newly created JWT Token that has not already been sent to Web3Auth or a Duplicate Token error will be thrown. It's a mandatory parameter as a string. |
subVerifierInfoArray? | Sub verifier info. It's an optional parameter as a TorusSubVerifierInfo[]. |
serverTimeOffset? | Server time offset. It's an optional parameter as a number. |
export type LoginParams = {
verifier: string;
verifierId: string;
idToken: string;
subVerifierInfoArray?: TorusSubVerifierInfo[];
serverTimeOffset?: number;
};
TorusSubVerifierInfo
- Table
- Interface
Parameter | Description |
---|---|
verifier | Details of the verifier (verifier type, ie. torus , metamask , auth etc.). It's a string mandatory parameter. |
idToken | A newly created JWT Token that has not already been sent to Web3Auth or a Duplicate Token error will be thrown. It's a string mandatory parameter. |
export interface TorusSubVerifierInfo {
verifier: string;
idToken: string;
}
Usage
await web3auth.connect({
verifier: "verifier-name", // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId: "verifier-id-value", // e.g. `Yux1873xnibdui` or `name@email.com` replace with your verifier id(sub or email)'s value.
idToken: "JWT Token", // replace with your newly created unused JWT Token.
});
Get a native provider
provider()
Returns the native provider that can be used to make different blockchain transactions.
Returns
get provider(): IProvider | null;
Get sessionId
sessionId()
Returns the sessionId of the user as a string.
Returns
get sessionId(): string;
Authenticate the user
authenticateUser()
Returns a promise of the UserAuthInfo
object containing the idToken
of the user.
Returns
authenticateUser(): Promise<UserAuthInfo>;
UserAuthInfo
export type UserAuthInfo = {
idToken: string;
};
Add a new chain
addChain(chainConfig: CustomChainConfig)
Add chain configuration to the web3auth instance.
Variable | Description |
---|---|
chainConfig | Mandatory chain-specific configuration as a CustomChainConfig type. |
CustomChainConfig
- Table
- Type Declarations
Parameter | Description |
---|---|
chainNamespace | Namespace of the chain. It's a mandatory parameter as a ChainNamespaceType type. |
chainId | The chain id of the chain. It's a mandatory parameter as a string . |
rpcTarget | RPC target URL for the chain. It's a mandatory parameter as a string . |
wsTarget | Web socket target URL for the chain. It's an optional parameter as a string . |
displayName | Display Name for the chain. It's an optional parameter as a string . |
blockExplorerUrl | URL of the block explorer. It's an optional parameter as a string . |
ticker | Default currency ticker of the network (e.g: ETH). It's an optional parameter as a string . |
tickerName | Name for currency ticker (e.g: Ethereum ). It's an optional parameter as a string . |
decimals | Number of decimals for the currency ticker (e.g: 18). It's an optional parameter as a number . |
logo | Logo for the token. It's an optional parameter as a string . |
isTestnet | Whether the network is testnet or not. It's an optional parameter as a boolean . |
export declare const ADAPTER_NAMESPACES: {
readonly EIP155: "eip155";
readonly SOLANA: "solana";
readonly CASPER: "casper";
readonly XRPL: "xrpl";
readonly MULTICHAIN: "multichain";
};
declare type ChainNamespaceType = (typeof CHAIN_NAMESPACES)[keyof typeof CHAIN_NAMESPACES];
export type CustomChainConfig = {
chainNamespace: ChainNamespaceType;
/**
* The chain id of the chain
*/
chainId: string;
/**
* RPC target Url for the chain
*/
rpcTarget: string;
/**
* web socket target Url for the chain
*/
wsTarget?: string;
/**
* Display Name for the chain
*/
displayName?: string;
/**
* Url of the block explorer
*/
blockExplorerUrl?: string;
/**
* Default currency ticker of the network (e.g: ETH)
*/
ticker?: string;
/**
* Name for currency ticker (e.g: `Ethereum`)
*/
tickerName?: string;
/**
* Number of decimals for the currency ticker (e.g: 18)
*/
decimals?: number;
/**
* Logo for the token
*/
logo?: string;
/**
* Whether the network is testnet or not
*/
isTestnet?: boolean;
};
Switch the chain
switchChain(params: {chainId: string;})
Switch to one of the added chains
Variable | Description |
---|---|
chainId | Id of the chain to switch to. It's a mandatory parameter as a string |
Logging out the user
logout()
Logs out the user and clears the session.
@web3auth/single-factor-auth
SDK only works for users who have not enabled MFA.
For MFA enabled users, you'll see
Error("User has already enabled mfa, please use the @webauth/webauth-web sdk for login with mfa");
Wallet Services Plugin Methods
You can use the Wallet Services Plugin to enable additional functionalities like showing the Wallet UI Screen, Wallet Connect Scanner, and initiating topup for the user.
Learn more about the Wallet Services Plugin in the Wallet Services SDK Reference.
Show WalletConnect Scanner
You can use the showWalletConnectScanner
function to show the Wallet Connect Scanner, and connect
with dApps having Wallet Connect login option. This is useful for interoperability with dApps having
Wallet Connect login option.
Learn more about showWalletConnectScanner
.
Fiat On Ramp
You can use the showCheckout
function to show the TopUp modal, allowing users to select their
local currency and specify the token to top up their wallet.
Learn more about showCheckout
.
Embedded Wallet UI
You can use the showWalletUI
function to show the templated wallet UI services.
Learn more about showWalletUI
.
Transaction Confirmatons Screen
You can use the wallet services provider to integrate prebuilt transaction confirmation screens into your application. Upon successful completion, you can retrieve the signature for the request. Learn more about transaction confirmation screens.
Example
Custom JWT Example
import { Web3Auth } from "@web3auth/single-factor-auth";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import jwt from "jsonwebtoken";
import fs from "fs";
// Use "openssl genrsa -out privateKey.pem 2048" to generate a private key
// Also, use this private key to generate a public key using "openssl rsa -in privateKey.pem -pubout -out publicKey.pem"
// Convert PEM to JWKS and expose it on a public URL, and make a web3auth verifier using that.
// Check out https://web3auth.io/docs/auth-provider-setup/byo-jwt-provider/ for more details.
var privateKey = fs.readFileSync("privateKey.pem");
// Define the chain config according to the chain you want to connect to
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",
};
// Instantiate Ethereum Provider
const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });
// Instantiate Web3Auth SFA SDK
const web3authSfa = new Web3Auth({
clientId: "WEB3AUTH_CLIENT_ID", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // Replace with your network name
privateKeyProvider,
usePnPKey: false, // Setting this to true returns the same key as PnP Web SDK, By default, this SDK returns CoreKitKey.
});
// Initialize Web3Auth SFA SDK
await web3authSfa.init();
const user = {
id: "faj2720i2fdG7NsqznOKrthDvq43", // must be unique to each user
name: "Mohammad Shahbaz Alam",
email: "shahbaz@web3auth.io",
profileImage: "https://avatars.githubusercontent.com/u/46641595?v=4",
};
// Login the user
const web3authSfaprovider = await web3auth.connect({
verifier: "web3auth-sfa-verifier", // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId: user.id, // e.g. `Yux1873xnibdui` or `name@email.com` replace with your verifier id(sub or email)'s value.
idToken: jwt.sign(
{
sub: user.id, // must be unique to each user
name: user.name,
email: user.email,
picture: user.profileImage,
aud: "urn:my-resource-server", // -> to be used in Custom Authentication as JWT Field
iss: "https://my-authz-server", // -> to be used in Custom Authentication as JWT Field
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 60 * 60,
},
privateKey, // <-- privateKey to sign the JWT Token
{ algorithm: "RS256", keyid: "1bb9605c36e69386830202b2d" },
), // or replace it with your newly created unused JWT Token.
});
// Get the private key, The private key returned here is the CoreKit Key, since the usePnPKey is set to false.
const ethPrivateKey = await web3authSfaprovider.request({ method: "eth_private_key" });
const eth_accounts = await web3authSfaprovider.request({ method: "eth_accounts" });
console.log("ETH Private Key", ethPrivateKey);
Firebase JWT Example
import { Web3Auth, decodeToken } from "@web3auth/single-factor-auth";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import { GoogleAuthProvider, getAuth, signInWithPopup, UserCredential } from "firebase/auth";
// Define the chain config according to the chain you want to connect to
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",
};
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyB0nd9YsPLu-tpdCrsXn8wgsWVAiYEpQ_E",
authDomain: "web3auth-oauth-logins.firebaseapp.com",
projectId: "web3auth-oauth-logins",
storageBucket: "web3auth-oauth-logins.appspot.com",
messagingSenderId: "461819774167",
appId: "1:461819774167:web:e74addfb6cc88f3b5b9c92",
};
// Instantiate Ethereum Provider
const privateKeyProvider = new EthereumPrivateKeyProvider({ config: { chainConfig } });
// Instantiate Web3Auth SFA SDK
const web3authSfa = new Web3Auth({
clientId: "WEB3AUTH_CLIENT_ID", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET, // Replace with your network name
privateKeyProvider,
usePnPKey: false, // Setting this to true returns the same key as PnP Web SDK, By default, this SDK returns CoreKitKey.
});
// Initialize Web3Auth SFA SDK
await web3authSfa.init();
// Initialize Firebase and get idToken from Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
const res = await signInWithPopup(auth, googleProvider);
const idToken = await res.user.getIdToken(true);
// get sub value from firebase id token
const { payload } = decodeToken(token); // parseToken is a function that parses the token and returns the payload.
// Login the user
const web3authSfaprovider = await web3auth.connect({
verifier: "web3auth-sfa-verifier", // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId: (payload as any).sub, // e.g. `Yux1873xnibdui` or `name@email.com` replace with your verifier id(sub or email)'s value.
idToken: idToken, // or replace it with your newly created unused JWT Token.
});
// Get the private key, The private key returned here is the CoreKit Key, since the usePnPKey is set to false.
const ethPrivateKey = await web3authSfaprovider.request({ method: "eth_private_key" });
const eth_accounts = await web3authSfaprovider.request({ method: "eth_accounts" });
console.log("ETH Private Key", ethPrivateKey);