Firebase Dart Admin Auth SDK
  • Firebase Dart Admin Auth SDK
    • Introduction
    • Getting Started
      • Installation
      • Initialize Firebase
    • User Management
      • Create User With Email and Password
      • Update Current User
      • Sign In With Credential
      • Sign In With Custom Token
      • Sign in with Email Link
      • Sign In Anonymously
      • Sign Out
      • Sign In With Redirect
      • Sign In With Popup
      • Sign in with Phone Number
      • Sign In With Email and Password
    • User Profile & Data
      • Update Profile
      • Get ID Token
      • Get ID Token Result
      • Reload user
      • Delete User
    • Email & Password Actions
      • Apply Action Code
      • Send Email Verification
      • Send Password Reset Email
      • Update Password
      • Verify Before Update Email
      • Verify Password Reset Code
      • Send Password Reset Email
      • Send Sign-in Link To Email
      • Confirm Password Reset
      • Check Action Code
    • Authentication State
      • Before Auth State Changed
      • On ID Token Changed
      • On Auth State Changed
    • Credential Management
      • Is Sign In With Email Link
      • Unlink Provider
      • Link With Credential
      • Fetch Sign In Methods For Email
      • Link With Popup
      • Link With Phone Number
    • Initialization & Configuration
      • Set Persistence
      • Connect Emulator
      • Use Device Language
      • Set Language Code
      • Initialize Recaptcha Config
      • Get Auth
      • Initialize Auth
    • Multi-Factor Authentication
      • Get Multi-Factor Resolver
    • OAuth and Third-party Auth
      • Generate Custom Token
      • Get Redirect Result
      • Revoke Access Token
    • Utility Functions
      • Get Additional User Info
      • Parse Action Code URL
    • Examples and Tutorials
    • Contributing
    • FAQs
Powered by GitBook
On this page
  • Using service account with keys
  • Using environment variables
  • Using Service Account With Key Impersonation
  1. Firebase Dart Admin Auth SDK
  2. Getting Started

Initialize Firebase

PreviousInstallationNextUser Management

Last updated 9 months ago

After importing the firebase_dart_admin_auth_sdk into your Flutter project, as mentioned in the , 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.

Note: Keep your serviceAccountKey.json file private and not pushed to public repositories.

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('user005@gmail.com', 'password');
        
       final await userCredential = await FirebaseApp.firebaseAuth
       ?.signInWithEmailAndPassword('user005@gmail.com', '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('user005@gmail.com', 'password');
        
       final await userCredential = await FirebaseApp.firebaseAuth
       ?.signInWithEmailAndPassword('user005@gmail.com', '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('user005@gmail.com', 'password');
        
       final await userCredential = await FirebaseApp.firebaseAuth
       ?.signInWithEmailAndPassword('user005@gmail.com', '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.

previous step