Using Auth0 with Web3Auth Android SDK
This guide will cover the basics of how to use the Web3Auth Android SDK in your Android application with Auth0.
Demo APK: Download
Repository: https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/android/android-auth0-example
Quick Start
npx degit Web3Auth/web3auth-pnp-examples/android/android-auth0-example w3a-android-auth0-demo
# Open in Android Studio
How it works?
When integrating Web3Auth Android SDK with Auth0 Login the flow looks something like this:
When a user logs in with
Auth0
, Auth0 sends a JWTid_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 21 or newer.
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 are also supported as mentioned in the flows above. However for this guide, we’re preferring SPA since its implicit flow doesn’t require an application to host a backend server.
Setup
Setup your Auth0 Tenant
Add the following URLs for your app to the Allowed Web Origins field when configuring your Auth0 Application.
- Additional to your own URLs for the application, please add
- https://testing.openlogin.com/auth (for Web3Auth testnet used in demo applications) and
- https://app.openlogin.com/auth (for Web3Auth mainnet used in production applications).
- Additional to your own URLs for the application, please add
You will require
domain
andclientId
of the newly created application which you can copy from Auth0 Console.
Enable Social login
- Enable
Google
or other social provider on theAuthentication > Social
page of your Auth0 Dashboard. - Vist https://auth0.com/learn/social-login to learn more.
Enable SMS Passwordless
If you want to implement SMS Passwordless, then this section is for you. Else you can skip this.
- Enable
SMS
on theAuthentication > Passwordless
page of your Auth0 Dashboard. - Under
Settings
tab, add yourTwilio SID
andTwilio AuthToken
. - Also, update the
From
number on the same page, and click on theSave
button. - Next, enable your application under
Applications
tab, and click on theSave
button. - 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
If you're to use SMS Passwordless, please visit here to setup the Lock Screen of Auth0 from your Auth0 Dashboard.
Enable Email Passwordless
If you want to implement Email Passwordless, then this section is for you. Else you can skip this.
- Enable
Email
on theAuthentication > Passwordless
page of your Auth0 Dashboard. - Under
Settings
tab, updateFrom
andSubject
based on your need and click on theSave
button. - Next, enable your application under
Applications
tab, and click on theSave
button. - 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
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.
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 Web Application as the platform.
Select the Web3Auth Network as
Sapphire Devnet
. We recommend creating a project in thesapphire_devnet
ortesnet
network during development. While moving to a production environment, make sure to convert your project tosapphire_mainnet
or any of the legacy mainnet networkmainnet
,aqua
, orcyan
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.
Create Auth0 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
andAuth0 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.
You will require the
verifierName
of the newly created verifier andclientId
of the Plug and Play Project.- Choose a name of your choice for the verifier identifier.
Create SMS Passwordless Verifier
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 theJWT Verifier ID
and typename
. - Enter
https://{YOUR-DOMAIN}.auth0.com/.well-known/jwks.json
as yourJWKS 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}
- iss:
- 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.
You will require the
verifierName
of the newly created verifier andclientId
of the Plug and Play Project.- Choose a name of your choice for the verifier identifier.
Create Email Passwordless Verifier
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
andAuth0 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.
You will require the
verifierName
of the newly created verifier andclientId
of the Plug and Play Project.- Choose a name of your choice for the verifier identifier.
- Add
{YOUR_APP_PACKAGE_NAME}://auth
in the Whitelist URL field of the Web3Auth Dashboard.
Configure Deep Link
Open your app's AndroidManifest.xml
file and add the following deep link intent filter to your sign-in activity:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accept URIs: {YOUR_APP_PACKAGE_NAME}://* -->
<data android:scheme="{YOUR_APP_PACKAGE_NAME}" />
</intent-filter>
Make sure your sign-in activity launchMode is set to singleTop in your AndroidManifest.xml
<activity
android:launchMode="singleTop"
android:name=".YourActivity">
<!-- ... -->
</activity>
Using the Web3Auth SDK
To use the Web3Auth SDK, you'll 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 our SDK page.
For this guide, we will be using the Web3Auth Android SDK.
Installation
Add Web3Auth to Gradle
In your project-level settings.gradle
file, add JitPack repository:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url "https://jitpack.io" } // <-- Add this line
}
}
Then, in your app-level build.gradle
dependencies section, add the following:
dependencies {
// ...
implementation 'com.github.Web3Auth:web3auth-android-sdk:4.0.8'
}
Permissions
Open your app's AndroidManifest.xml
file and add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
Note: The
<uses-permission>
element must be a direct child of the<manifest>
root element
Initialization
Initialization is a two-step process:
Please note that these are the most critical steps where you must pass on different parameters according to the preference of your project. Additionally, You must configure Whitelabeling and Custom Authentication within this step if you wish to customize your Web3Auth Instance.
Create Web3Auth Instance
In your activity, create a Web3Auth
instance with your Web3Auth project's configurations.
web3Auth = Web3Auth(
Web3AuthOptions(
context = this,
clientId = getString(R.string.web3auth_project_id), // pass over your Web3Auth Client ID from Developer Dashboard
network = Network.MAINNET, // pass over the network you want to use (MAINNET, TESTNET, CYAN, AQUA )
redirectUrl = Uri.parse("{YOUR_APP_PACKAGE_NAME}://auth"), // your app's redirect URL
loginConfig = hashMapOf("jwt" to LoginConfigItem(
verifier = "web3auth-auth0-demo",
typeOfLogin = TypeOfLogin.JWT,
name = "Auth0 Login",
clientId = getString(R.string.web3auth_auth0_client_id)
)
)
)
)
// Handle user signing in when app is not alive
web3Auth.setResultUrl(intent?.data)
Add the below line to your app/res/values/strings.xml
file and paste your Web3Auth Client ID:
<resources>
<!-- ... -->
<string name="web3auth_project_id">CLIENT_ID_FROM_WEB3AUTH_DASHBOARD</string>
<!-- ... -->
</resources>
Read more about initialising the Android SDK here.
Set Result URL
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// Handle user signing in when app is active
web3Auth.setResultUrl(intent?.data)
}
Authentication
Logging in
Once initialized, you can use the web3Auth.login(LoginParams("{selectedLoginProvider}"))
function to authenticate the user when they click the login
button.
private fun signIn() {
val selectedLoginProvider = Provider.JWT // For Auth0, we use JWT, not AUTH0
val loginCompletableFuture: CompletableFuture<Web3AuthResponse> = web3Auth.login(LoginParams(selectedLoginProvider, extraLoginOptions = ExtraLoginOptions(domain = "https://shahbaz-torus.us.auth0.com", verifierIdField = "sub")))
loginCompletableFuture.whenComplete { loginResponse, error ->
if (error == null) {
// render logged in UI
println(loginResponse)
} else {
// render error UI
}
}
}
When connecting, the login
function takes the LoginParams arguments for the login. See the LoginParams for more
details.
Sample loginResponse
{
"privKey": "0ajjsdsd....",
"userInfo": {
"name": "John Dash",
"profileImage": "https://lh3.googleusercontent.com/a/Ajjjsdsmdjmnm...",
"typeOfLogin": "google",
"aggregateVerifier": "tkey-google",
"verifier": "torus",
"verifierId": "john@gmail.com",
"email": "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
},
"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
val userInfo = web3AuthResponse.userInfo
Using the web3Auth.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 or select Curve for your Android application, read the linked documentation.
Logout
private fun signOut() {
val logoutCompletableFuture = web3Auth.logout()
logoutCompletableFuture.whenComplete { _, error ->
if (error == null) {
// render logout UI
} else {
// render error UI
}
}
}
Logging out your user is as simple as calling the web3Auth.logout()
function.
Interacting with the Blockchain
Checkout the full codes to interact with the ETH Blockchain.
Get Account
// checkout the Connect Blockchain > Ethereum > Android to get full code.
private fun getAddress(): String {
println("Address:, ${credentials.address}")
return credentials.address
}
// Setup UI and event handlers
val getBalanceButton = findViewById<Button>(R.id.getBalanceButton)
getBalanceButton.setOnClickListener { getAddress() }
Get Balance
// checkout the Connect Blockchain > Ethereum > Android to get full code.
private fun getBalance(): BigInteger? {
val publicAddress = credentials.address
val ethBalance: EthGetBalance = web3.ethGetBalance(publicAddress, DefaultBlockParameterName.LATEST).sendAsync().get()
println("Balance: ${ethBalance.balance}")
return ethBalance.balance
}
// Setup UI and event handlers
val getBalanceButton = findViewById<Button>(R.id.getBalanceButton)
getBalanceButton.setOnClickListener { getBalance() }
Send Transaction
// checkout the Connect Blockchain > Ethereum > Android to get full code.
private fun sendTransaction(amount: Double, recipientAddress: String): String? {
val ethGetTransactionCount: EthGetTransactionCount = web3.ethGetTransactionCount(credentials.address, DefaultBlockParameterName.LATEST).sendAsync().get()
val nonce: BigInteger = ethGetTransactionCount.transactionCount
val value: BigInteger = Convert.toWei(amount.toString(), Convert.Unit.ETHER).toBigInteger()
val gasLimit: BigInteger = BigInteger.valueOf(21000)
val chainId: EthChainId = web3.ethChainId().sendAsync().get()
// Raw Transaction
val rawTransaction: RawTransaction = RawTransaction.createTransaction(
chainId.chainId.toLong(),
nonce,
gasLimit,
recipientAddress,
value,
"",
BigInteger.valueOf(5000000000),
BigInteger.valueOf(6000000000000)
)
val signedMessage: ByteArray = TransactionEncoder.signMessage(rawTransaction, credentials)
val hexValue: String = Numeric.toHexString(signedMessage)
val ethSendTransaction: EthSendTransaction = web3.ethSendRawTransaction(hexValue).sendAsync().get()
return if(ethSendTransaction.error != null) {
println("Tx Error: ${ethSendTransaction.error.message}")
ethSendTransaction.error.message
} else {
println("Tx Hash: ${ethSendTransaction.transactionHash}")
ethSendTransaction.transactionHash
}
}
// Setup UI and event handlers
val sendTransactionButton = findViewById<Button>(R.id.sendTransactionButton)
sendTransactionButton.setOnClickListener { sendTransaction() }
Example code
The code for the application we developed in this guide can be found in the Web3Auth Android Auth0 Example. Check it out and try running it locally yourself!
Also, checkout other examples:
- Using Web3Auth Android SDK
- Using Custom JWT (via Firebase) with Android SDK
- Using Aggregate Verifier with Android SDK
Questions?
Ask us on Web3Auth's Community Portal