Using of PnP Unity SDK
Once you've installed and successfully initialized Web3Auth, you can use it to authenticate your users.
Logging in a User
web3Auth.login(LoginParams)
This function helps your users to trigger the login process. The login flow is triggered based on the selected provider. You can view the list of selected providers in the provider section.
Additionally, you can associate a function to be triggered on successful login. This function receives the user's profile as a parameter.
void Start()
{
web3Auth = GetComponent<Web3Auth>();
web3Auth.setOptions(new Web3AuthOptions()
{
});
web3Auth.onLogin += onLogin;
}
private void onLogin(Web3AuthResponse response)
{
// Functions to be called after logging in your user
}
Arguments
web3Auth.login()
requires LoginParams
as a required input.
LoginParams
- Table
- Interface
Parameter | Description |
---|---|
loginProvider | It sets the OAuth login method to be used. You can use any of the supported values are GOOGLE , FACEBOOK , REDDIT , DISCORD , TWITCH , APPLE , LINE , GITHUB , KAKAO , LINKEDIN , TWITTER , WEIBO , WECHAT , EMAIL_PASSWORDLESS . |
extraLoginOptions? | It can be used to set the OAuth login options for corresponding loginProvider . For instance, you'll need to pass the user's email address as. The Default value for the field is null , and it accepts ExtraLoginOptions as a value. |
redirectUrl? | Url where user will be redirected after successfull login. By default user will be redirected to same page where login will be initiated. Default value for the field is null , and accepts URI as a value. |
appState? | It can be used to keep track of the app state when user will be redirected to app after login. Default is null , and accepts string as a value. |
mfaLevel? | Customize the MFA screen shown to the user during OAuth authentication. Default value for field is MFALevel.DEFAULT , which shows MFA screen every 3rd login. It accepts MFALevel as a value. |
dappShare? | Custom verifier logins can get a dapp share returned to them after a successful login. This is useful if the dapps want to use this share to allow users to login seamlessly. It accepts string as a value. |
curve? | It is used to determine the public key encoded in the jwt token which returned in getUserInfo function after user login. This parameter won't change the format of private key returned by Web3Auth. Private key returned by getPrivKey is always secp256k1. The default value is Curve.SECP256K1 . |
sessionTime? | It allows developers to configure the session management time. Session Time is in seconds, and takes an int as a value. |
public class LoginParams
{
public Provider loginProvider { get; set; }
public string dappShare { get; set; }
public ExtraLoginOptions extraLoginOptions { get; set; }
public Uri redirectUrl { get; set; }
public string appState { get; set; }
public MFALevel mfaLevel { get; set; }
public int sessionTime { get; set; }
public Curve curve { get; set; }
}
Provider
public enum Provider
{
[EnumMember(Value = "google")]
GOOGLE,
[EnumMember(Value = "facebook")]
FACEBOOK,
[EnumMember(Value = "reddit")]
REDDIT,
[EnumMember(Value = "discord")]
DISCORD,
[EnumMember(Value = "twitch")]
TWITCH,
[EnumMember(Value = "apple")]
APPLE,
[EnumMember(Value = "line")]
LINE,
[EnumMember(Value = "github")]
GITHUB,
[EnumMember(Value = "kakao")]
KAKAO,
[EnumMember(Value = "linkedin")]
LINKEDIN,
[EnumMember(Value = "twitter")]
TWITTER,
[EnumMember(Value = "weibo")]
WEIBO,
[EnumMember(Value = "wechat")]
WECHAT,
[EnumMember(Value = "email_passwordless")]
EMAIL_PASSWORDLESS,
[EnumMember(Value = "email_password")]
EMAIL_PASSWORD,
[EnumMember(Value = "jwt")]
JWT,
[EnumMember(Value = "CUSTOM_VERIFIER")]
CUSTOM_VERIFIER
}
ExtraLoginOptions
The LoginParams
class accepts the ExtraLoginOptions
as an optional input, containing advanced
options for custom authentication, email passwordless login, etc. This parameter can be considered
as advanced login options needed for specific cases.
LoginParams() { selectedLoginProvider, extraLoginOptions = ExtraLoginOptions() }
- Table
- Interface
Parameter | Description |
---|---|
additionalParams? | Additional params in Dictionary<string, string> format for OAuth login, use id_token(JWT) to authenticate with web3auth. |
domain? | Your custom authentication domain in string format. For example, if you are using Auth0, this could be example.au.auth0.com. |
client_id? | Client id in string format, provided by your login provider used for custom verifier. |
leeway? | The value used to account for clock skew in JWT expirations. The value is in the seconds, and ideally should be no more than 60 seconds, with a maxium of 120 seconds. It takes string as a value. |
verifierIdField? | The field in the JWT token that maps to verifier id. Please make sure you have selected the correct JWT verifier id in the Developer Dashboard. It takes string as a value. |
isVerifierIdCaseSensitive? | bool to confirm whether the verifier id field is case sensitive or not. |
display? | Allows developers to configure the display of UI. It takes Display as a value. |
prompt? | Prompt shown to the user during the authentication process. It takes Prompt as a value. |
max_age? | Maxium time allowed without reauthentication. If the last time the user authenticated is greater than this value, then the user must reauthenticate. It takes string as a value. |
ui_locales? | The space separated list of language tags, ordered by preference. For example fr-CA fr en . |
id_token_hint? | It specify the previously issued ID token. It takes string as a value. |
id_token? | JWT (ID Token) to be passed for login. |
login_hint? | It is used to send the user's email address during Email Passwordless login. It takes string as a value. |
acr_values? | acr_values |
scope? | The default scope to be used on authentication requests. The defaultScope defined in the Auth0Client is included along with this scope. It takes string as a value. |
audience? | The audience, presented as the aud claim in the access token, defines the intended consumer of the token. It takes string as a value. |
connection? | The name of the connection configured for your application. If null, it will redirect to the Auth0 Login Page and show the Login Widget. It takes string as a value. |
state? | state |
response_type? | Defines which grant to be execute for the authorization server. It takes string as a value. |
nonce? | nonce value |
redirect_uri? | It can be used to specify the default URL, where your custom JWT verifier can redirect your browser to with the result. If you are using Auth0, it must be whitelisted in the Allowed Callback URLs in your Auth0's application. |
public class ExtraLoginOptions {
public Dictionary<string, string> additionalParams { get; set; }
public string domain { get; set; }
public string client_id { get; set; }
public string leeway { get; set; }
public string verifierIdField { get; set; }
public bool isVerifierIdCaseSensitive { get; set; }
public Display display { get; set; }
public Prompt prompt { get; set; }
public string max_age { get; set; }
public string ui_locales { get; set; }
public string id_token_hint { get; set; }
public string login_hint { get; set; }
public string id_token { get; set; }
public string acr_values { get; set; }
public string scope { get; set; }
public string audience { get; set; }
public string connection { get; set; }
public string state { get; set; }
public string response_type { get; set; }
public string nonce { get; set; }
public string redirect_uri { get; set; }
}
Curve
The LoginParams
class accepts a curve
parameter. This parameter can be used to select the
elliptic curve to use for the signature.
LoginParams() { selectedLoginProvider, curve = Curve.SECP256K1 }
- SECP256K1
- ED25519
public void login()
{
var selectedProvider = Provider.GOOGLE;
var options = new LoginParams()
{
loginProvider = selectedProvider,
curve = Curve.SECP256K1
};
web3Auth.login(options);
}
public void login()
{
var selectedProvider = Provider.GOOGLE;
var options = new LoginParams()
{
loginProvider = selectedProvider,
curve = Curve.ED25519
};
web3Auth.login(options);
}
Sample Response
{
"ed25519PrivKey": "666523652352635....",
"privKey": "0ajjsdsd....",
"coreKitKey": "0ajjsdsd....",
"coreKitEd25519PrivKey": "666523652352635....",
"sessionId": "....",
"error": "....",
"userInfo": {
"aggregateVerifier": "w3a-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
"isMfaEnabled": true // returns true if user has enabled mfa
}
}
Example
- Discord
- Twitch
- Email Passwordless
- JWT
public void login()
{
var selectedProvider = Provider.GOOGLE;
var options = new LoginParams()
{
loginProvider = selectedProvider
};
web3Auth.login(options);
}
public void login()
{
var selectedProvider = Provider.FACEBOOK;
var options = new LoginParams()
{
loginProvider = selectedProvider
};
web3Auth.login(options);
}
public void login()
{
var selectedProvider = Provider.DISCORD;
var options = new LoginParams()
{
loginProvider = selectedProvider
};
web3Auth.login(options);
}
public void login()
{
var selectedProvider = Provider.TWITCH;
var options = new LoginParams()
{
loginProvider = selectedProvider
};
web3Auth.login(options);
}
public void login()
{
var selectedProvider = Provider.EMAIL_PASSWORDLESS;
var options = new LoginParams()
{
loginProvider = selectedProvider,
extraLoginOptions = new ExtraLoginOptions()
{
login_hint = "hello@web3auth.io"
}
};
web3Auth.login(options);
}
public void login()
{
var selectedProvider = Provider.JWT;
var options = new LoginParams()
{
loginProvider = selectedProvider,
extraLoginOptions = new ExtraLoginOptions()
{
id_token = "your_jwt_token"
}
};
web3Auth.login(options);
}
Session Management
The Session Management feature allows you to check the existing sessions with Web3Auth. The
Web3AuthState
will allow users to remain authenticated with Web3Auth for 1 day by default, or a
maximum of 7 days, or until the user logout or session data is cleared.
The Web3Auth login
function accepts a sessionTime
parameter.
public void login()
{
var selectedProvider = Provider.GOOGLE;
var options = new LoginParams()
{
loginProvider = selectedProvider,
sessionTime = 86400,
};
web3Auth.login(options);
}
Enable MFA for a user
The enableMFA
method is used to trigger MFA setup flow for users. The method takes LoginParams
which will used during custom verifiers. If you are using default login providers, you don't need to
pass LoginParams
. If you are using custom jwt verifiers, you need to pass the JWT token in
loginParams
as well.
Additionally you can associate a function to be triggered on successful MFA Enabled.
void Start()
{
web3Auth = GetComponent<Web3Auth>();
web3Auth.setOptions(new Web3AuthOptions()
{
});
web3Auth.onMFASetup += onMFASetup;
}
private void onMFASetup(bool response)
{
// Functions to be called after user logs out
}
- Default Verifier
- Custom JWT Verifier
{
var selectedProvider = Provider.GOOGLE;
var options = new LoginParams()
{
loginProvider = selectedProvider,
};
web3Auth.enableMFA(options);
}
{
var selectedProvider = Provider.JWT;
var options = new LoginParams()
{
loginProvider = selectedProvider,
extraLoginOptions = new ExtraLoginOptions()
{
domain = "https://web3auth.au.auth0.com",
verifierIdField = "sub",
prompt = Prompt.LOGIN,
}
};
web3Auth.enableMFA(options);
}
Launch Wallet Services
The launchWalletServices
method launches a WebView which allows you to use the templated wallet UI
services. The method takes ChainConfig
as the required input. Wallet Services is currently only
available for EVM chains.
Access to Wallet Services is gated. You can use this feature in sapphire_devnet
for free. The
minimum pricing plan to use this feature in a production
environment is the Scale Plan.
Arguments
ChainConfig
- Table
- Class
Parameter | Description |
---|---|
chainNamespace | Custom configuration for your preferred blockchain. As of now only EVM supported. Default value is ChainNamespace.eip155 . |
decimals? | Number of decimals for the currency ticker. Default value is 18, and accepts int as value. |
blockExplorerUrl? | Blockchain's explorer URL. (eg: https://etherscan.io ) |
chainId | The chain id of the selected blockchain in hex String . |
displayName? | Display Name for the chain. |
logo? | Logo for the selected chainNamespace & chainId . |
rpcTarget | RPC Target URL for the selected chainNamespace & chainId . |
ticker? | Default currency ticker of the network (e.g: ETH ) |
tickerName? | Name for currency ticker (e.g: Ethereum ) |
using System.Collections.Generic;
#nullable enable
public class ChainConfig {
public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.EIP155;
public int decimals { get; set; } = 18;
public string blockExplorerUrl { get; set; } = null;
public string chainId { get; set; }
public string displayName { get; set; } = null;
public string logo { get; set; } = null;
public string rpcTarget { get; set; }
public string ticker { get; set; } = null;
public string tickerName { get; set; } = null;
}
Usage
{
var chainConfig = new ChainConfig()
{
chainId = "0x1",
rpcTarget = rpcURL,
ticker = "ETH",
chainNamespace = Web3Auth.ChainNamespace.EIP155
};
web3Auth.launchWalletServices(chainConfig);
}
Request signature
web3Auth.request()
The request
method facilitates the use of templated transaction screens for signing transactions.
Please check the list of JSON RPC methods, noting that the request method currently supports only the signing methods.
Arguments
Arguments | Description |
---|---|
chainConfig | Defines the chain to be used for signature. |
method | JSON RPC method name in String . Currently, the request method only supports the singing methods. |
requestParams | Parameters for the corresponding method. The parameters should be in the list and correct sequence. Take a look at RPC methods to know more. |
Additionally you can associate a getSignResponse
function to retrieve the signature for the
request.
void Start()
{
web3Auth = GetComponent<Web3Auth>();
web3Auth.setOptions(new Web3AuthOptions()
{
});
web3Auth.onSignResponse += onSignResponse;
}
private void onSignResponse(SignResponse signResponse)
{
// Functions to be called after user logs out
}
Example
public void PopupSignMessageUI() {
var chainConfig = new ChainConfig()
{
chainId = "0xaa36a7",
rpcTarget = "https://rpc.ankr.com/eth_sepolia",
ticker = "ETH",
chainNamespace = Web3Auth.ChainNamespace.EIP155
};
JArray paramsArray = new JArray
{
"Hello World",
account.Address,
"Android"
};
web3Auth.request(chainConfig, "personal_sign", paramsArray);
}
private void onSignResponse(SignResponse signResponse)
{
Debug.Log("Retrieved SignResponse: " + signResponse);
updateConsole("Retrieved SignResponse: " + signResponse);
}
Logging out a user
web3Auth.logout()
Trigger logout flow. This function doesn't take parameters. A completable future containing a void object will be returned on successfull logout otherwise an error response is returned.
Additionally you can associate a function to be triggered on successful logout.
void Start()
{
web3Auth = GetComponent<Web3Auth>();
web3Auth.setOptions(new Web3AuthOptions()
{
});
web3Auth.onLogout += onLogout;
}
private void onLogout()
{
// Functions to be called after user logs out
}
Example
public void logout()
{
web3Auth.logout();
Debug.Log("Logged out!");
}
Working Example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using TMPro;
using Nethereum.Web3;
using Nethereum.Util;
using Nethereum.Signer;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.ABI.Encoders;
using Nethereum.Hex.HexTypes;
using Nethereum.Web3.Accounts;
using Nethereum.Web3.Accounts.Managed;
public class Web3AuthScript : MonoBehaviour
{
Web3Auth web3Auth;
public TextMeshProUGUI console;
private string userEmail = "";
private string privateKey;
private string userInfo;
private Account account;
Web3 web3;
const string rpcURL = "https://rpc.ankr.com/eth";
// Start is called before the first frame update
void Start()
{
// IMP START - Quick Start
web3Auth = GetComponent<Web3Auth>();
// IMP END - Quick Start
// IMP START - SDK Initialization
// IMP START - Dashboard Registration
var clientId = "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ"; // Get your Web3Auth Client ID on https://dashboard.web3auth.io
// IMP END - Dashboard Registration
web3Auth.setOptions(new Web3AuthOptions()
{
clientId = clientId,
redirectUrl = new System.Uri("w3aexample://com.web3auth.unityexample/auth"),
network = Web3Auth.Network.SAPPHIRE_MAINNET,
});
// IMP END - SDK Initialization
web3Auth.onLogin += onLogin;
web3Auth.onLogout += onLogout;
updateConsole("Ready to Login!");
}
public void GrabEmailFromInputField(string input)
{
userEmail = input;
}
public void login()
{
if (userEmail == "")
{
Debug.Log("Please enter your email.");
updateConsole("Please enter your email.");
return;
}
// IMP START - Login
var selectedProvider = Provider.EMAIL_PASSWORDLESS;
var options = new LoginParams()
{
loginProvider = selectedProvider,
extraLoginOptions = new ExtraLoginOptions()
{
login_hint = userEmail
}
};
web3Auth.login(options);
// IMP END - Login
}
private void onLogin(Web3AuthResponse response)
{
// IMP START - Get User Information
userInfo = JsonConvert.SerializeObject(response.userInfo, Formatting.Indented);
// IMP END - Get User Information
// IMP START - Blockchain Calls
privateKey = response.privKey;
var newAccount = new Account(privateKey);
account = newAccount;
var rpc = new Nethereum.JsonRpc.Client.RpcClient(new System.Uri(rpcURL));
web3 = new Web3(account, rpc);
// IMP END - Blockchain Calls
Debug.Log(JsonConvert.SerializeObject(response, Formatting.Indented));
updateConsole(JsonConvert.SerializeObject(response, Formatting.Indented));
}
public void getUserInfo()
{
if (account == null)
{
Debug.Log("Please Login First");
updateConsole("Please Login First");
return;
}
Debug.Log(userInfo);
updateConsole(userInfo);
}
public void logout()
{
// IMP START - Logout
web3Auth.logout();
// IMP END - Logout
}
private void onLogout()
{
privateKey = null;
userInfo = null;
account = null;
Debug.Log("Logged out!");
updateConsole("Logged out!");
}
// IMP START - Blockchain Calls
public void getAccount()
{
if (account == null)
{
Debug.Log("Please Login First");
updateConsole("Please Login First");
return;
}
Debug.Log(account.Address);
updateConsole(account.Address);
}
public void getBalance()
{
if (account == null)
{
Debug.Log("Please Login First");
updateConsole("Please Login First");
return;
}
var balance = web3.Eth.GetBalance.SendRequestAsync(account.Address).Result.Value;
Debug.Log(balance);
updateConsole(balance.ToString());
}
public void signMessage()
{
if (account == null)
{
Debug.Log("Please Login First");
updateConsole("Please Login First");
return;
}
var msg = "wee test message 18/09/2017 02:55PM";
var signer = new EthereumMessageSigner();
var signature = signer.EncodeUTF8AndSign(msg, new EthECKey(privateKey));
Debug.Log(signature);
updateConsole(signature.ToString());
}
// IMP END - Blockchain Calls
public void updateConsole(string message)
{
console.text = message;
}
// IMP START - Enable MFA
public void enableMFA()
{
var selectedProvider = Provider.JWT;
var options = new LoginParams()
{
loginProvider = selectedProvider,
extraLoginOptions = new ExtraLoginOptions()
{
domain = "https://web3auth.au.auth0.com",
verifierIdField = "sub",
prompt = Prompt.LOGIN,
}
};
web3Auth.enableMFA(options);
}
// IMP END - Enable MFA
private void onMFASetup(bool response)
{
Debug.Log("MFA Setup: " + response);
}
// IMP START - Launch Wallet Services
public void launchWalletServices()
{
var chainConfig = new ChainConfig()
{
chainId = "0x1",
rpcTarget = rpcURL,
ticker = "ETH",
chainNamespace = Web3Auth.ChainNamespace.EIP155
};
web3Auth.launchWalletServices(chainConfig);
}
// IMP END - Launch Wallet Services
// Update is called once per frame
void Update()
{
}
}