Initialize Firebase

After importing the firebase_dart_admin_auth_sdk into your Flutter project, as mentioned in the previous step, it's time to initialize Firebase using the SDK.

There are two methods you can use to achieve this:

  • Using environment variables

  • Using service account methods

Using Environment Variables

To use environment variables to initialize Firebase, first obtain your project ID and API key.

Your project ID can be found in the general tab of your "Project settings" page via the link:

https://console.firebase.google.com/u/0/project/<your-project-name>/settings/general

Your project API key can be found via the Google cloud console link:

https://console.cloud.google.com/apis/credentials?authuser=0&project=<your-project-name>

Set the environment variables for your project ID and API key as follows:

set FIREBASE_API_KEY=your_api_key
set FIREBASE_PROJECT_ID=your_project_id

Initialize Firebase with environment variables.

   import 'package:firebase_dart_admin_auth_sdk/firebase_dart_admin_auth_sdk.dart';
   
   
   void main() async {
     //Pass the enviroment variables into the function below, I.E API key and project ID
     FirebaseApp.initializeAppWithEnvironmentVariables(
       apiKey: FIREBASE_API_KEY,
       projectId: FIREBASE_PROJECT_ID,
     );
      
     // Get Firebase auth instance for this project
     FirebaseApp.instance.getAuth();

     // Example: Sign in with email and password
     try {
       final user = await FirebaseApp.firebaseAuth
        ?.createUserWithEmailAndPassword('[email protected]', 'password');
        
       final await userCredential = await FirebaseApp.firebaseAuth
       ?.signInWithEmailAndPassword('[email protected]', 'password'); 
       
       print('Signed in as ${userCredential?.user.email}');
     } catch (e) {
       print('Sign-in error: $e');
     }
   }

Use the FirebaseApp.initializeAppWithEnvironmentVariables() method to initialize Firebase passing in the environment variables.

Try signing in a user with the FirebaseApp.firebaseAuth?.signInWithEmailAndPassword() authentication method, passing in required arguments. If login is successful, a return user's credential userCredential is returned.

Using the environment variables to initialize Firebase currently works on backend and frontend (all platforms).

Initializing Firebase using the Firebase Dart Admin Auth SDK with the FirebaseApp.initializeAppWithEnvironmentVariables() method allows for user creation and management on both the client and server side.

Optional: Use Firebase Web SDK for frontend, OR use this SDK on backend for user operations.

Environment Variables can be used for:

  • ✅ Backend user creation

  • ✅ Password resets

  • ✅ Authentication

  • ❌ Token verification

Using Service Account Methods

To obtain the service account keys follow the steps below:

  • Login into your Firebase console.

  • Click on the Firebase project you want to get the service keys.

  • Click on the gear icon in "Project Overview" on the left sidebar

  • Click on "Project settings".

  • Select the "Service account" tab on the "Project settings" page.

  • Click the "Generate new private key" button to download your serviceAccountKey.json file.

  • Save the serviceAccountKey.json file with your project directory.

Firebase can be initialized using various service account methods. To use any of these methods you'll first get your service account email.

To get your service account email, use the Google cloud console link:

https://console.cloud.google.com/iam-admin/iam?authuser=0&hl=en&project=<your-project-name>

The service accounts methods for SDK initialization:

  • FirebaseApp.initializeAppWithServiceAccount()

  • FirebaseApp.initializeAppWithServiceAccountImpersonation()

  • FirebaseApp.initializeAppWithServiceAccountImpersonationGCP()

  • FirebaseApp.initializeAppWithWorkloadIdentity()

  • FirebaseApp.initializeAppWithWorkloadIdentityFederation()

Using service account with keys

After getting your service account key, use the FirebaseApp.initializeAppWithServiceAccount() method to initialize Firebase. See the example code snippet below:

   import 'package:firebase_dart_admin_auth_sdk/firebase_dart_admin_auth_sdk.dart';
   import 'package:flutter/services.dart' show rootBundle;
   
   
   void main() async {
      //To initialize with service account put the path to the json file in the function below
      String serviceAccountContent = await rootBundle.loadString(
          'assets/service_account.json'); //Add your own JSON service account
     
     // Initialize Firebase with the service account content
      await FirebaseApp.initializeAppWithServiceAccount(
        serviceAccountContent: serviceAccountContent,
        serviceAccountKeyFilePath: '',
      );
      
      // Get Firebase auth instance for this project
      FirebaseApp.instance.getAuth();

     // Example: verify ID token
     try {
      final verifiedToken = await FirebaseApp.firebaseAuth?.verifyIdToken(clientIdToken);
        
     } catch (e) {
       print('verification error: $e');
     }
   }

The serviceAccountContent variable indicates the path to the serviceAccountKey.json file you got from your Firebase console.

Initialize the FirebaseApp class using the .initializeAppWithServiceAccount() method passing in the serviceAccountContent and serviceAccountKayFilePath file path as arguments.

An FirebaseApp auth instance is created and you can test out signing in a user with their email and password. The user credential userCredential is returned on successful sign-in.

Using service account without key impersonation

The example below shows how to initialize Firebase with the FirebaseApp.initializeAppWithServiceAccountImpersonation() method.

   import 'package:firebase_dart_admin_auth_sdk/firebase_dart_admin_auth_sdk.dart';
   
   
   void main() async {
    String serviceAccountEmail = 'service_account_email';
    String userEmail = 'user_email';
    
    //To initialize with service account impersonation, pass the service account content and impersonated email as shown below
     await FirebaseApp.initializeAppWithServiceAccountImpersonation(
       serviceAccountContent: serviceAccountContent,
       impersonatedEmail: impersonatedEmail,
     );
      
     // Get Firebase auth instance for this project
     FirebaseApp.instance.getAuth();

     // Example: verify ID token
     try {
       final verifiedToken = await FirebaseApp.firebaseAuth?.verifyIdToken(clientToken);
     } catch (e) {
       print('Verification error: $e');
     }
   }

The FirebaseApp.initializeAppWithServiceAccountImpersonation() method takes a service account email serviceAccountEmail , and the user email userEmail , as required arguments for Firebase initialization.

The service account methods of Firebase initialization should be used only for admin operations in the backend.

Service Account can be used for:

  • ✅ Token verification

  • ✅ Admin operations

  • ❌ User creation (frontend must handle)

Once Firebase has been initialized, the instance becomes a focal point for accessing and using all authentication functions and interacting with Firebase services.

Last updated