Using Auth0 with Web3Auth iOS SDK
This guide will cover the basics of how to use the Web3Auth iOS SDK in your Swift application with Auth0.
Repository: https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/ios/ios-auth0-example
Quick Start
npx degit Web3Auth/web3auth-pnp-examples/ios/ios-auth0-example w3a-ios-auth0-demo
# Open in Xcode
How it works?
When integrating Web3Auth iOS 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
-
iOS 13+
-
Xcode 11.4+ / 12.x
-
Swift 4.x / 5.x
-
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 prefer 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 URLs for the application, please add
-
You will require the
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. - Visit 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. Otherwise, you can skip this.
- Enable
SMS
on theAuthentication > Passwordless
page of your Auth0 Dashboard. - Under the
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 the
Applications
tab, and click on theSave
button. - You can test sending an SMS from the
Try
tab. Once, an 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 set up 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. Otherwise, you can skip this.
- Enable
Email
on theAuthentication > Passwordless
page of your Auth0 Dashboard. - Under the
Settings
tab, updateFrom
andSubject
based on your need and click on theSave
button. - Next, enable your application under the
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 set up 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
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:
-
Pick a name of your choice for the verifier identifier.
eg. auth0-project
-
Choose
Social Login Providers
and selectAuth0
from the Login Provider dropdown. -
Next, 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. And, selectSub
orEmail
as the JWT Verifier ID. -
Click on the
Create Verifier
button to create your verifier. It may take up to 10-20 minutes to deploy the verifier on Sapphire Devnet. 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. -
Create SMS Passwordless Verifier
If you want to implement SMS Passwordless, then this section is for you. Otherwise, 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 Providers
from the Login Provider. -
Choose
Custom
for theJWT Verifier ID
and typename
. -
Enter
https://{YOUR-DOMAIN}/.well-known/jwks.json
as yourJWKS Endpoint
. This will be used to validate the JWT token issued by Auth0. eg.https://web3auth.eu.auth0.com/.well-known/jwks.json
-
JWT validation fields:
- iss:
https://{YOUR-DOMAIN}
- aud:
{AUTH0-CLIENT-ID}
- iss:
-
Click on the
Create
button to create your verifier. It may take up to 10-20 minutes to deploy the verifier on Sapphire Devnet. 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. -
Create Email Passwordless Verifier
If you want to implement Email Passwordless, then this section is for you. Otherwise, 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
-
Choose
Social Login Providers
and selectAuth0
from the Login Provider dropdown. -
Choose your Authentication Type as
Email 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 the
Create
button to create your verifier. It may take up to 10-20 minutes to deploy the verifier on Sapphire Devnet. 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. -
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 iOS 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 iOS SDK.
Installation
Swift Package Manager
-
In Xcode, with your app project open, navigate to File > Add Package Dependencies.
-
When prompted, add the Web3Auth iOS SDK repository:
https://github.com/Web3Auth/web3auth-swift-sdk
From the
Dependency Rule
dropdown, selectExact Version
and enter8.1.1
as the version. -
When finished, Xcode will automatically begin resolving and downloading your dependencies in the background.
Cocoapods
To install the Web3Auth SDK using Cocoapods, follow the below steps:
- Open the Podfile, and add the Web3Auth pod:
pod 'Web3Auth', '~> 8.1.1'
- Once added, use
pod install
command to download the Web3Auth dependency.
Configuration
To use Web3Auth for iOS you need to Whitelist your bundleId your project.
- Go to Web3Auth Developer Dashboard, and create or open an existing Web3Auth project.
- Whitelist
(bundleId)://auth
in the developer dashboard. This step is mandatory for the redirect to work.
After Installation, the next step to use Web3Auth is to Initialize the SDK. However, the Initialization can be done in 2 ways,
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.
Initialization
Initialization can be done in 2 ways,
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.
With Web3Auth.plist
In your application bundle add a plist file named Web3Auth.plist
with the following information:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ClientId</key>
<string>YOUR_OPENLOGIN_CLIENT_ID</string>
<key>Network</key>
<string>mainnet | testnet</string>
</dict>
</plist>
When you have a Web3Auth.plist
and you have specified your Web3Auth configuration there, you can
simply construct your Web3Auth instance with
import Web3Auth
let web3auth = Web3Auth()
Without Web3Auth.plist
If you don't have a Web3Auth.plist or want to use optional configuration parameters, you can construct the Web3Auth instance with
import Web3Auth
let web3auth = Web3Auth(W3AInitParams(
clientId: "<your clientId>",
network: .MAINNET,
loginConfig: [
TypeOfLogin.jwt.rawValue:
.init(
verifier: "<Your verifier id from Web3Auth Dashboard>",
typeOfLogin: .jwt,
clientId: "<Your Auth0 ClientId>"
)
],
sdkUrl: ...,
redirectUrl: ...,
))
Authentication
Logging in
Once initialized, you can use the Web3Auth.login(W3ALoginParams("{selectedLoginProvider}"))
function to authenticate the user when they click the login button.
let result = try await Web3Auth(.init(
clientId: clientId,
network: network,
loginConfig: [
TypeOfLogin.jwt.rawValue:
.init(
verifier: "web3auth-auth0-example",
typeOfLogin: .jwt,
name: "Web3Auth-Auth0-JWT",
clientId: "294QRkchfq2YaXUbPri7D6PH7xzHgQMT"
)
]
)).login(
W3ALoginParams(
loginProvider: .JWT,
dappShare: nil,
extraLoginOptions: ExtraLoginOptions(
display: nil, prompt: nil,
max_age: nil, ui_locales: nil, id_token_hint: nil, id_token: nil,
login_hint: nil, acr_values: nil, scope: nil, audience: nil,
connection: nil, domain: "https://shahbaz-torus.us.auth0.com",
client_id: nil, redirect_uri: nil, leeway: nil, verifierIdField: "sub",
isVerifierIdCaseSensitive: nil
),
mfaLevel: .NONE,
curve: .SECP256K1
))
When connecting, the login
function takes the W3ALoginParams arguments for the login. See the
W3ALoginParams 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 Web3AuthState
var user: Web3AuthState?
var userInfo = user?.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 Swift application, read the linked documentation.
Logout
// Assuming the user is logged in, logout the user
Web3Auth.logout()
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.
Mainnet Block Explorer URL: https://etherscan.io -- chainId: "1"
import web3
import Web3Auth
var user: Web3AuthState
var client: EthereumClientProtocol
var address: EthereumAddress
var account: EthereumAccount
var latestBlock = 0
var chainID = 5
var providerUrl = "https://rpc.ankr.com/eth"
Get Account
// checkout the Connect Blockchain > Ethereum > iOS to get full code.
account = try EthereumAccount(keyStorage: user )
address = account.address
Get Balance
// checkout the Connect Blockchain > Ethereum > iOS to get full code.
client = EthereumClient(url: URL(string: RPC_URL)!)
latestBlock = client.eth_blockNumber
let balance = try client.eth_getBalance(address: address, block:latestBlock)
Send Transaction
// checkout the Connect Blockchain > Ethereum > iOS to get full code.
import BigInt
import Foundation
import web3
public typealias Ether = Double
public typealias Wei = BigUInt
public final class TorusWeb3Utils {
public static func timeMinToSec(val: Double) -> Double {
return val * 60
}
// NOTE: calculate wei by 10^18
private static let etherInWei = pow(Double(10), 18)
private static let etherInGwei = pow(Double(10), 9)
/// Convert Wei(BInt) unit to Ether(Decimal) unit
public static func toEther(wei: Wei) -> Ether {
guard let decimalWei = Double(wei.description) else {
return 0
}
return decimalWei / etherInWei
}
public static func toEther(Gwie: BigUInt) -> Ether {
guard let decimalWei = Double(Gwie.description) else {
return 0
}
return decimalWei / etherInGwei
}
/// Convert Ether(Decimal) unit to Wei(BInt) unit
public static func toWei(ether: Ether) -> Wei {
let wei = Wei(ether * etherInWei)
return wei
}
/// Convert Ether(String) unit to Wei(BInt) unit
public static func toWei(ether: String) -> Wei {
guard let decimalEther = Double(ether) else {
return 0
}
return toWei(ether: decimalEther)
}
// Only used for calcurating gas price and gas limit.
public static func toWei(GWei: Double) -> Wei {
return Wei(GWei * 1000000000)
}
}
let gasPrice = try await client.eth_gasPrice()
let maxTipInGwie = BigUInt(TorusWeb3Utils.toEther(Gwie: BigUInt(amount)))
let totalGas = gasPrice + maxTipInGwie
let amtInGwie = TorusWeb3Utils.toWei(ether: amount)
let nonce = try await client.eth_getTransactionCount(address: address, block: .Latest)
let transaction = EthereumTransaction(from: address, to: EthereumAddress(sendTo), value: amtInGwie, data: Data(), nonce: nonce + 1, gasPrice: totalGas, gasLimit: gasLimit, chainId: chainID)
let signed = try account.sign(transaction: transaction)
let val = try await client.eth_sendRawTransaction(signed.transaction, withAccount: account)
Example code
The code for the application we developed in this guide can be found in the Web3Auth iOS Auth0 Example. Check it out and try running it locally yourself!
Also, checkout other example:
Questions?
Ask us on Web3Auth's Community Support Portal