Skip to content

Commit 71a2362

Browse files
add sfa-android-guide
1 parent a9d9d8c commit 71a2362

2 files changed

Lines changed: 259 additions & 0 deletions

File tree

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
---
2+
title: Using Firebase with Web3Auth Android SFA SDK
3+
image: "guides/banners/sfa-android-firebase.png"
4+
description:
5+
Web3Auth Single Factor Authentication (SFA) Android SDK with Firebase enables secure blockchain
6+
authentication using Email and Password login. The process involves setting up Firebase and
7+
Web3Auth, initializing the SDK, and interacting with the Ethereum blockchain.
8+
type: guide
9+
tags: [mobile, android, ethereum, SFA]
10+
date: May 19, 2024
11+
author: Web3Auth Team
12+
---
13+
14+
import SEO from "@site/src/components/SEO";
15+
import TabItem from "@theme/TabItem";
16+
import Tabs from "@theme/Tabs";
17+
18+
<SEO
19+
title="Using Firebase with Web3Auth Android SFA SDK"
20+
description="Learn how to use Web3Auth Single Factor Auth with Firebase in your Android Application."
21+
image="https://web3auth.io/docs/guides/banners/sfa-android-firebase.png"
22+
slug="/guides/sfa-android-firebase"
23+
/>
24+
25+
In this guide, we'll talk about how we can use Web3Auth Single Factor Auth with Firebase in your
26+
Android application.
27+
28+
As an overview, the guide is quite simple, with functionality to log in, display user details, and
29+
perform blockchain interactions. The signing of the blockchain transactions is done through the
30+
Web3Auth embedded wallet. You can check out the infrastructure docs,
31+
["Web3Auth Wallet Management Infrastructure"](/docs/infrastructure/infrastructure) for a high-level
32+
overview of the Web3Auth architecture and implementation. For those who want to skip straight to the
33+
code, you can find it on
34+
[GitHub](https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/single-factor-auth-android/sfa-android-quick-start).
35+
36+
## How to set up Web3Auth Dashboard
37+
38+
If you haven't already, sign up on the Web3Auth platform. It is free and gives you access to the
39+
Web3Auth's base plan. After the basic setup, explore other features and functionalities offered by
40+
the Web3Auth Dashboard. It includes custom verifiers, whitelabeling, analytics, and more. Head to
41+
[Web3Auth's documentation](/docs/dashboard-setup) page for detailed instructions on setting up the
42+
Web3Auth Dashboard.
43+
44+
## How to set up Firebase for Android
45+
46+
If you haven't already setup the Firebase for your Android app, please setup the Firebase, as it's
47+
the prerequisites for the guide. Head to the
48+
[Firebase's documentation](https://firebase.google.com/docs/android/setup) for the details
49+
instructions.
50+
51+
## How to set up Custom verifier
52+
53+
Once, you have set up the Web3Auth Dashboard, created a new project, and set up Firbase, it's time
54+
to create a Custom Verifier for your Firebase application. We already have detail instructions on
55+
how to create a Custom Verifier for Firebase, please head to our
56+
[documentation](https://web3auth.io/docs/auth-provider-setup/authentication-service-providers#firebase).
57+
58+
## Integrating Web3Auth SFA in Android
59+
60+
Once, you have set up the Custom Verifier, it's time to integrate Web3Auth in your Android
61+
application. For the implementation, we'll use the "single-factor-auth-android". This SDK
62+
facilitates integration with Web3Auth. This way you can easily manage embedded wallet in your
63+
Android application.
64+
65+
### Installation
66+
67+
In your module-level `build.gradle` or `settings.gradle` file, add JitPack repository:
68+
69+
```groovy
70+
dependencyResolutionManagement {
71+
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
72+
repositories {
73+
google()
74+
mavenCentral()
75+
// highlight-next-line
76+
maven { url "https://jitpack.io" } // <-- Add this line
77+
}
78+
}
79+
```
80+
81+
Once, you have added the JitPack repository, then in your app-level `build.gradle` dependencies
82+
section, add the `single-factor-auth-android`.
83+
84+
```groovy
85+
dependencies {
86+
// ...
87+
// highlight-next-line
88+
implementation 'com.github.web3auth:single-factor-auth-android:0.0.6'
89+
}
90+
```
91+
92+
For the prerequisites, and other mandatory configuration of the SDK, please head to our
93+
[installation documentation](/docs/sdk/core-kit/sfa-android/install.mdx).
94+
95+
### Initialization
96+
97+
After successfully installing the package, the next step is to initialize `SingleFactorAuth` in your
98+
Android app. This sets up the necessary configurations using Web3Auth network and prepares the SDK.
99+
[Learn more about SingleFactorAuth Initialization](/docs/sdk/core-kit/sfa-android/initialize.mdx).
100+
101+
```kotlin
102+
class MainActivity : AppCompatActivity() {
103+
private lateinit var singleFactorAuth: SingleFactorAuth
104+
private lateinit var singleFactorAuthArgs: SingleFactorAuthArgs
105+
106+
// Additional code
107+
108+
override fun onCreate(savedInstanceState: Bundle?) {
109+
super.onCreate(savedInstanceState)
110+
setContentView(R.layout.activity_main)
111+
112+
// highlight-start
113+
singleFactorAuthArgs = SingleFactorAuthArgs(TorusNetwork.TESTNET)
114+
singleFactorAuth = SingleFactorAuth(singleFactorAuthArgs)
115+
// highlight-end
116+
}
117+
118+
// Additional code
119+
}
120+
```
121+
122+
### Session Management
123+
124+
To check whether the user is authenticated, you can use the `initialize` method. For a user already
125+
authenticated, the result would be a non-nullable `TorusKey`. You can navigate to different views
126+
based on the result.
127+
128+
```kotlin
129+
val sessionResponse: CompletableFuture<TorusKey> = singleFactorAuth.initialize(
130+
this.applicationContext
131+
)
132+
133+
sessionResponse.whenComplete {
134+
torusKey, error ->
135+
if (torusKey != null) {
136+
publicAddress = torusKey?.publicAddress.toString()
137+
println("""Private Key: ${torusKey.privateKey?.toString(16)}""".trimIndent())
138+
} else {
139+
Log.d("MainActivity_SFA", error.message ?: "Something went wrong")
140+
}
141+
}
142+
```
143+
144+
### Authentication
145+
146+
If the user is not authenticated, you should utilize the `getKey` method. For the guide, we will add
147+
Email Password login using Firebase. The `getKey` method is pretty straightforward in
148+
SingleFactorAuth and takes `LoginParams` as input. After successfully logging in, the method will
149+
return the `TorusKey`.
150+
151+
Learn more about [SingleFactorAuth LoginParams](/docs/sdk/core-kit/sfa-android/usage#loginparams).
152+
153+
```kotlin
154+
private var auth: FirebaseAuthauth = Firebase.auth
155+
156+
// Take the input for email and password from user
157+
auth.signInWithEmailAndPassword("android@firebase.com", "Android@Web3Auth")
158+
.addOnCompleteListener(this) {
159+
task ->
160+
if (task.isSuccessful) {
161+
// Sign in success, update UI with the signed-in user's information
162+
Log.d(TAG, "signInWithEmail:success")
163+
val user = auth.currentUser
164+
165+
// Try to get a fresh idToken
166+
user!!.getIdToken(true).addOnSuccessListener {
167+
result ->
168+
val idToken = result.token
169+
170+
Log.d(TAG, "GetTokenResult result = $idToken")
171+
172+
if (idToken != null) {
173+
val sub = user!!.id
174+
175+
val loginParams = LoginParams(
176+
// Replace with your custom verifier name
177+
"web3auth-firebase-examples",
178+
sub,
179+
idToken
180+
)
181+
182+
try {
183+
// Save the TorusKey for future use to interact with Blockchain.
184+
// highlight-start
185+
torusKey = singleFactorAuth.getKey(
186+
loginParams,
187+
this.applicationContext,
188+
86400
189+
).get()
190+
// highlight-end
191+
192+
} catch (e: ExecutionException) {
193+
e.printStackTrace()
194+
} catch (e: InterruptedException) {
195+
e.printStackTrace()
196+
}
197+
198+
publicAddress = torusKey?.publicAddress.toString()
199+
200+
println("""Private Key: ${torusKey?.privateKey?.toString(16)}""".trimIndent())
201+
println("""Public Address: $publicAddress""".trimIndent())
202+
203+
// Additional code
204+
};
205+
}
206+
} else {
207+
// Upon failur, display a message to the user.
208+
Log.w(TAG, "signInWithEmail:failure", task.exception)
209+
Toast.makeText(
210+
baseContext, "Authentication failed.",
211+
Toast.LENGTH_SHORT
212+
).show()
213+
}
214+
}
215+
```
216+
217+
## Set up Blockchain Providers
218+
219+
Once we have successfully authenticated the user, the next step would be to fetch the user details,
220+
retrieve wallet address and prepare blockchain providers for interactions. For this guide, we are
221+
supporting only Ethereum ecosystem, but the general idea can be used for any blockchain ecosystem.
222+
223+
For interacting with ethereum chains, we'll use the [web3j](https://github.com/hyperledger/web3j)
224+
SDK. For installation, in your app-level build.gradle's dependencies section, add the web3j
225+
dependency.
226+
227+
```groovy
228+
dependencies {
229+
// ...
230+
implementation 'org.web3j:core:4.8.7-android'
231+
}
232+
```
233+
234+
After successfully installing SDK, it's time to `Credentials` instance to retrive user's EOA
235+
address, and interact with blockchain. To retrive the user's private key, we'll use the `TorusKey`
236+
instance.
237+
238+
```kotlin
239+
// highlight-next-line
240+
val credentials: Credentials = Credentials.create(torusKey!.privateKey!.toString(16))
241+
242+
// User's EOA address
243+
Log.d(TAG, credentials.address)
244+
```
245+
246+
To retrive user's balance, and interacting with Blockcahin, you can follow our detailed guide on how
247+
to
248+
[interact with EVM chain guides](https://web3auth.io/docs/connect-blockchain/evm/ethereum/android#get-balance).
249+
Since, you already have created `Credentials` instance, and retrived the user's EOA address, you can
250+
skip that part.
251+
252+
## Conclusion
253+
254+
Voila, you have learned how to use Web3Auth SFA SDK with Android application.
255+
256+
If you are interested in learning more about SFA SDK, please checkout our
257+
[documentation for Android SFA SDK](/docs/sdk/core-kit/sfa-android/). You can find the code used for
258+
the guide on our
259+
[examples repo](https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/single-factor-auth-android/sfa-android-quick-start).
1.09 MB
Loading

0 commit comments

Comments
 (0)