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 three methods you can use to achieve this:

  • Using service account with keys

  • Using environment variables

  • Using service account without key impersonation

Using service account with keys

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.

After getting your service account key, use it to initialize Firebase.

   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: 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');
     }
   }

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 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 for Flutter web, other methods work for mobile.

{% hint style="warning" %}
**Warning hints** are good for showing important information or non-critical warnings.
{% endhint %}

Using Service Account With Key Impersonation

Firebase can be initialized using service account with key impersonation method. To use this method 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>
   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, pass the service account email and user email as shown below
     FirebaseApp.initializeAppWithServiceAccountImpersonation(
     serviceAccountEmail: serviceAccountEmail, 
     userEmail: userEmail
     );
      
     // 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');
     }
   }

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

A FirebaseApp instance, is created and the FirebaseApp.firebaseAuth?.signInWithEmailAndPassword() authentication option is used to verify initialization was successful.

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