@@ -8,6 +8,7 @@ import Tiles from "@theme/Tiles";
88
99import CustomConnectionOptions from " @site/static/images/dashboard/authentication-custom-connections.png" ;
1010import FirebaseConnection from " @site/static/images/dashboard/firebase-connection.png" ;
11+ import JwtLoginFirebase from " ../../sdk/web/react/advanced/_custom-authentication-snippets/_jwt_login_firebase.mdx" ;
1112
1213Firebase is a popular backend platform that enables developers to seamlessly integrate
1314authentication, databases, and other services into their applications. Web3Auth supports Firebase as
@@ -112,96 +113,240 @@ Follow these steps to create a Firebase connection:
112113
113114## Usage
114115
115- ### Initialize Web3Auth
116-
117- Wrap your app with the ` Web3AuthProvider ` . This provider should be as close to the root of your
118- React tree as possible.
119-
120- ``` js title="Example: React + Vite (main.tsx)"
121- import { StrictMode } from " react" ;
122- import { createRoot } from " react-dom/client" ;
123- import " ./index.css" ;
124-
125- import { Web3AuthProvider , WEB3AUTH_NETWORK } from " @web3auth/modal/react" ;
126-
127- import App from " ./App.tsx" ;
128-
129- createRoot (document .getElementById (" root" )! ).render (
130- < StrictMode>
131- < Web3AuthProvider
132- config= {{
133- web3AuthOptions: {
134- clientId: " WEB3AUTH_CLIENT_ID" , // Replace with your Client ID
135- web3AuthNetwork: WEB3AUTH_NETWORK .SAPPHIRE_DEVNET ,
136- },
137- }}
138- >
139- < App / >
140- < / Web3AuthProvider>
141- < / StrictMode>
142- );
143- ```
144-
145116Since, the ` Firebase Connection ` details are available from Dashboard, developers don't need to pass
146117any additional parameters to the ` Web3AuthProvider ` .
147118
148119> Follow our [ Quickstart Guide] ( /quick-start ) to setup the basic flow.
149120
150- ### Login with Firebase
151-
152- ``` jsx
153- import { useWeb3AuthConnect , WALLET_CONNECTORS , AUTH_CONNECTION } from " @web3auth/modal/react" ;
154- import { useAccount } from " wagmi" ;
155-
156- import { initializeApp } from " firebase/app" ;
157- import { getAuth , GithubAuthProvider , signInWithPopup } from " firebase/auth" ;
158-
159- // Firebase configuration
160- const firebaseConfig = {
161- apiKey: " get-your-firebase-api-key" ,
162- authDomain: " get-your-firebase-auth-domain" ,
163- projectId: " get-your-firebase-project-id" ,
164- storageBucket: " get-your-firebase-storage-bucket" ,
165- messagingSenderId: " get-your-firebase-messaging-sender-id" ,
166- appId: " get-your-firebase-app-id" ,
167- };
168-
169- function LoginPage () {
170- const { connectTo } = useWeb3AuthConnect ();
171- const { address } = useAccount ();
172-
173- const loginWithFirebase = async () => {
174- try {
175- const app = initializeApp (firebaseConfig);
176- const auth = getAuth (app);
177- const githubProvider = new GithubAuthProvider ();
178-
179- // Using Github provider for demo purposes
180- const result = await signInWithPopup (auth, githubProvider);
181-
182- const idToken = await result .user .getIdToken (true );
183-
184- // focus-start
185- await connectTo (WALLET_CONNECTORS .AUTH , {
186- authConnectionId: " firebase-auth-connection-id" ,
187- authConnection: AUTH_CONNECTION .CUSTOM ,
188- idToken,
189- extraLoginOptions: {
190- isUserIdCaseSensitive: false ,
191- },
192- });
193- // focus-end
194- } catch (error) {
195- console .error (" Firebase authentication error:" , error);
121+ ### Web
122+
123+ <JwtLoginFirebase />
124+
125+ ### Android
126+
127+ ##### Create Web3Auth Instance
128+
129+ In your activity, create a ` Web3Auth ` instance with your Web3Auth project's configurations.
130+
131+ ``` kotlin
132+ web3Auth = Web3Auth (
133+ Web3AuthOptions (
134+ context = this ,
135+ clientId = getString(R .string.web3auth_project_id), // pass over your Web3Auth Client ID from Developer Dashboard
136+ network = Network .SAPPHIRE_MAINNET
137+ redirectUrl = Uri .parse(" {YOUR_APP_PACKAGE_NAME}://auth" ), // your app's redirect URL
138+ // focus-start
139+ loginConfig = hashMapOf(" jwt" to LoginConfigItem (
140+ verifier = " web3auth-firebase-examples" ,
141+ typeOfLogin = TypeOfLogin .JWT ,
142+ name = " Firebase Login" ,
143+ clientId = getString(R .string.web3auth_project_id)
144+ )
145+ )
146+ // focus-end
147+ )
148+ )
149+
150+ // Handle user signing in when app is not alive
151+ web3Auth.setResultUrl(intent?.data)
152+ ```
153+
154+ ##### Logging in
155+
156+ Once initialized, you can use the ` web3Auth.login(LoginParams("{selectedLoginProvider}")) ` function
157+ to authenticate the user when they click the login button.
158+
159+ ``` kotlin
160+ private fun signIn () {
161+ // focus-start
162+ auth = Firebase .auth
163+ auth.signInWithEmailAndPassword(" android@firebase.com" , " Android@Web3Auth" )
164+ // focus-end
165+ .addOnCompleteListener(this ) { task ->
166+ if (task.isSuccessful) {
167+ // Sign in success, update UI with the signed-in user's information
168+ Log .d(TAG , " signInWithEmail:success" )
169+ val user = auth.currentUser
170+ user!! .getIdToken(true ).addOnSuccessListener { result ->
171+ val idToken = result.token
172+
173+ Log .d(TAG , " GetTokenResult result = $idToken " )
174+ val selectedLoginProvider = Provider .JWT
175+ // focus-start
176+ val loginCompletableFuture: CompletableFuture <Web3AuthResponse > = web3Auth.login(
177+ LoginParams (
178+ selectedLoginProvider,
179+ extraLoginOptions = ExtraLoginOptions (
180+ domain = " firebase" , id_token = idToken
181+ )
182+ )
183+ )
184+ // focus-end
185+
186+ loginCompletableFuture.whenComplete { loginResponse, error ->
187+ if (error == null ) {
188+ println (loginResponse)
189+ reRender(loginResponse)
190+ } else {
191+ Log .d(" MainActivity_Web3Auth" , error.message ? : " Something went wrong" )
192+ }
193+ }
194+ }
195+ } else {
196+ // If sign in fails, display a message to the user.
197+ Log .w(TAG , " signInWithEmail:failure" , task.exception)
198+ Toast .makeText(baseContext, " Authentication failed." ,
199+ Toast .LENGTH_SHORT ).show()
200+
201+ }
202+ }
203+ }
204+ ```
205+
206+ When connecting, the ` login ` function takes the LoginParams arguments for the login. See the
207+ [ LoginParams] ( /sdk/mobile/pnp/android/usage#parameters ) for more details.
208+
209+ ### Flutter
210+
211+ ##### Create Web3Auth Instance
212+
213+ In your ` main.dart ` file, initialize the ` Web3AuthFlutter ` plugin at the very beginning such as in
214+ the overriden ` initState ` function
215+
216+ ``` dart
217+ @override
218+ void initState() {
219+ super.initState();
220+ initPlatformState();
221+ }
222+
223+ Future<void> initPlatformState() async {
224+ final Uri redirectUrl;
225+ if (Platform.isAndroid) {
226+ redirectUrl = Uri.parse('{SCHEME}://{HOST}/auth');
227+ } else if (Platform.isIOS) {
228+ redirectUrl = Uri.parse('{bundleId}://auth');
229+ } else {
230+ throw UnKnownException('Unknown platform');
231+ }
232+
233+ // focus-start
234+ final loginConfig = HashMap<String, LoginConfigItem>();
235+
236+ loginConfig['jwt'] = LoginConfigItem(
237+ verifier: "VERIFIER_NAME", // get it from web3auth dashboard
238+ typeOfLogin: TypeOfLogin.jwt,
239+ name: "Firebase JWT Login",
240+ clientId: "WEB3AUTH_CLIENT_ID", // web3auth's plug and play client id
241+ );
242+
243+ await Web3AuthFlutter.init(
244+ Web3AuthOptions(
245+ clientId:'YOUR WEB3AUTH CLIENT ID FROM DASHBOARD',
246+ network: Network.cyan,
247+ redirectUri: redirectUrl,
248+ loginConfig: loginConfig,
249+ )
250+ );
251+ // focus-end
252+
253+ await Web3AuthFlutter.initialize();
254+ }
255+ ```
256+
257+ ##### Logging in
258+
259+ Once initialized, you can use the
260+ ` Web3AuthFlutter.login(LoginParams( loginProvider: Provider.google )) ` function to authenticate the
261+ user when they click the login button.
262+
263+ ``` dart
264+ Future<Web3AuthResponse> _withJWT() async {
265+ String idToken = "";
266+ try {
267+ // focus-start
268+ final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
269+ email: 'custom+id_token@firebase.login',
270+ password: 'Welcome@W3A',
271+ );
272+
273+ idToken = await credential.user?.getIdToken(true) ?? '';
274+ // focus-end
275+ } on FirebaseAuthException catch (e) {
276+ if (e.code == 'user-not-found') {
277+ log('No user found for that email.');
278+ } else if (e.code == 'wrong-password') {
279+ log('Wrong password provided for that user.');
196280 }
197- };
198-
199- return (
200- < div>
201- < button onClick= {() => loginWithFirebase ()}> Login with Firebase< / button>
202- < p> Address: {address}< / p>
203- {/* 0x176513A0A18ad0502dEbd3108999D4D146cA23D2 */ }
204- < / div>
281+ }
282+
283+ // focus-start
284+ return Web3AuthFlutter.login(
285+ LoginParams(
286+ loginProvider: Provider.jwt,
287+ extraLoginOptions: ExtraLoginOptions(
288+ id_token: idToken,
289+ domain: 'firebase',
290+ ),
291+ ),
205292 );
293+ // focus-end
294+ }
295+ ```
296+
297+ Read more about initializing the Flutter SDK [ here] ( /sdk/mobile/pnp/flutter/initialize ) .
298+
299+ ### React Native
300+
301+ ``` tsx
302+ const web3auth = new Web3Auth (WebBrowser , SecureStore , {
303+ clientId ,
304+ network: OPENLOGIN_NETWORK .SAPPHIRE_MAINNET , // SAPPHIRE_MAINNET or SAPPHIRE_DEVNET
305+ loginConfig: {
306+ // focus-start
307+ jwt: {
308+ verifier: " YOUR_JWT_VERIFIER_NAME" , // Please create a verifier on the developer dashboard and pass the name here
309+ typeOfLogin: " jwt" ,
310+ },
311+ // focus-end
312+ },
313+ });
314+ ```
315+
316+ ``` tsx
317+ import auth from " @react-native-firebase/auth" ;
318+ import { GoogleSignin } from " @react-native-google-signin/google-signin" ;
319+
320+ async function signInWithFirebase() {
321+ try {
322+ GoogleSignin .configure ({
323+ webClientId: " 461819774167-5iv443bdf5a6pnr2drt4tubaph270obl.apps.googleusercontent.com" ,
324+ });
325+ // Check if your device supports Google Play
326+ await GoogleSignin .hasPlayServices ({ showPlayServicesUpdateDialog: true });
327+ // Get the user's ID token
328+ const { idToken } = await GoogleSignin .signIn ();
329+ // Create a Google credential with the token
330+ const googleCredential = auth .GoogleAuthProvider .credential (idToken );
331+
332+ // Sign-in the user with the credential
333+ const res = await auth ().signInWithCredential (googleCredential );
334+
335+ const idToken = await res .user .getIdToken (true );
336+
337+ // focus-start
338+ await web3auth .login ({
339+ redirectUrl: resolvedRedirectUrl ,
340+ mfaLevel: " default" , // Pass on the MFA level of your choice: default, optional, mandatory, none
341+ loginProvider: " jwt" ,
342+ extraLoginOptions: {
343+ id_token: idToken ,
344+ verifierIdField: " sub" , // same as your JWT Verifier ID on the dashboard
345+ },
346+ });
347+ // focus-end
348+ } catch (error ) {
349+ console .error (error );
350+ }
206351}
207352```
0 commit comments