ESP32/ESP8266: Firebase Authentication (Email and Password)

In this guide, you’ll learn how to authenticate to Firebase using your ESP32 or ESP8266 board with an email and password. This is useful for restricting or allowing access to certain users or creating multiple users that can access the same Firebase project. Additionally, this is helpful to set up database rules to protect your project’s data.

ESP32 ESP8266 Firebase Authentication Email Password

Other Firebase Tutorials with the ESP32 that you might be interested in:

What is Firebase?

Firebase logo

Firebase is Google’s mobile application development platform that helps you build, improve, and grow your app. It has many services used to manage data from any android, IOS, or web application like authentication, realtime database, hosting, etc. In this tutorial, we’ll focus on the authentication part.

Project Overview

  1. Create Firebase Project
  2. Set Authentication Methods
  3. Get Project API Key
  4. Authentication with ESP32/ESP8266

1) Create Firebase Project

1) Go to Firebase and sign in using a Google Account.

2) Click Get Started and then Add project to create a new project.

3) Give a name to your project, for example: ESP Firebase Demo.

Set Up Firebase Project for ESP32 and ESP8266 Step 1

4) Disable the option Enable Google Analytics for this project as it is not needed and click Create project.

Set Up Firebase Project for ESP32 and ESP8266 Step 2

5) It will take a few seconds to set up your project. Then, click Continue when it’s ready.

6) You’ll be redirected to your Project console page.

2) Set Authentication Methods

To allow authentication with email and password, first, you need to set authentication methods for your app.

“Most apps need to know the identity of a user. In other words, it takes care of logging in and identifying the users (in this case, the ESP32 or ESP8266). Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.” To learn more about the authentication methods, you can read the documentation.

1) On the left sidebar, click on Authentication and then on Get started.

Firebase Project Authentication

2) Select the Option Email/Password.

Selecting Firebase Authentication with Email/Password

3) Enable that authentication method and click Save.

Enable Email/password authentication Firebase

4) The authentication with email and password should now be enabled.

Firebase Authentication with Email/Password enabled

5) Now, you need to add a user. Still on the Authentication tab, select the Users tab at the top. Then, click on Add User.

Firebase Authentication Add New User

6) Add an email address for the authorized user. It can be your google account email or any other email. You can also create an email for this specific project. Add a password that will allow you to sign in to your app and access the database. Don’t forget to save the password in a safe place because you’ll need it later. When you’re done, click Add user.

Firebase Authentication Add User with Email and Password

7) A new user was successfully created and added to the Users table.

Firebase Users Table

Notice that Firebase creates a unique UID for each registered user. The user UID allows us to identify the user and keep track of the user to provide or deny access to the project or the database. There’s also a column that registers the date of the last sign-in. At the moment, it is empty because we haven’t signed in with that user yet.

3) Get Project API Key

To interface with your Firebase project using the ESP32 or ESP8266 boards, you need to get your project API key. Follow the next steps to get your project API key.

1) On the left sidebar, click on Project Settings.

Firebase Project Settings

2) Copy the Web API Key to a safe place because you’ll need it later.

Firebase Project Settings Web API Key

4) Authentication with ESP32/ESP8266

Now that your Firebase Project is created and you’ve set up the authentication method, you’ll learn to log in with the ESP32 using the authorized user email and password.

To program the ESP32, you can use Arduino IDE, VS Code with the PlatformIO extension, or other suitable software.

Note: for firebase projects, we recommend using VS Code with the PlatformIO extension because if you want to develop a web application to make the bridge between the ESP32 and Firebase, VS Code provides all the tools to do that. However, we won’t build the web application in this tutorial, so you can use Arduino IDE.

Install the Firebase-ESP-Client Library

There is a library with lots of examples to use Firebase with the ESP32: the Firebase-ESP-Client library. This library is compatible with both the ESP32 and ESP8266 boards.

If you like this library and you’ll use it in your projects, consider supporting the developer’s work.

In this tutorial, we’ll look at a simple example to authenticate the ESP32. The library provides many other examples that you can check here. It also offers detailed documentation explaining how to use the library.

Installation – VS Code + PlatformIO

If you’re using VS Code with the PlatformIO extension, click on the PIO Home icon and select the Libraries tab. Search for “Firebase ESP Client“. Select the Firebase Arduino Client Library for ESP8266 and ESP32.

Install Firebase ESP Client Library VS Code

Then, click Add to Project and select the project you’re working on.

Add Firebase ESP Client Library to Project VS Code

Also, change the monitor speed to 115200 by adding the following line to the platformio.ini file of your project:

monitor_speed = 115200

Installation – Arduino IDE

If you’re using Arduino IDE, follow the next steps to install the library.

  1. Go to Sketch > Include Library > Manage Libraries
  2. Search for Firebase ESP Client and install the Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz.
Install Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz

Now, you’re all set to start programming the ESP32 or ESP8266 board to interact with the database.

ESP32/ESP8266 Firebase Authentication Email/Password

Copy the following code to the Arduino IDE or to the main.cpp file if you’re using VS Code.

/*
  Rui Santos
  Complete project details at our blog: https://RandomNerdTutorials.com/esp32-esp8266-firebase-authentication/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Based in the Authenticatiions Examples by Firebase-ESP-Client library by mobizt: https://github.com/mobizt/Firebase-ESP-Client/tree/main/examples/Authentications
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Insert Firebase project API Key
#define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "[email protected]"
#define USER_PASSWORD "your_user_password"

// Define Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

// Variable to save USER UID
String uid;

// Initialize WiFi
void initWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
  Serial.println();
}

void setup(){
  Serial.begin(115200);
  
  // Initialize WiFi
  initWiFi();

  // Assign the api key (required)
  config.api_key = API_KEY;

  // Assign the user sign in credentials
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  Firebase.reconnectWiFi(true);
  fbdo.setResponseSize(4096);

  // Assign the callback function for the long running token generation task
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

  // Assign the maximum retry of token generation
  config.max_token_generation_retry = 5;

  // Initialize the library with the Firebase authen and config
  Firebase.begin(&config, &auth);

  // Getting the user UID might take a few seconds
  Serial.println("Getting User UID");
  while ((auth.token.uid) == "") {
    Serial.print('.');
    delay(1000);
  }
  // Print user UID
  uid = auth.token.uid.c_str();
  Serial.print("User UID: ");
  Serial.print(uid);
}

void loop(){
  if (Firebase.isTokenExpired()){
    Firebase.refreshToken(&config);
    Serial.println("Refresh token");
  }
}

View raw code

You need to insert your network credentials, URL database, and project API key for the project to work.

This sketch was based on the authentication basic example provided by the library. You can find more examples here.

How the Code Works

Continue reading to learn how the code works, or skip to the demonstration section.

Include Libraries

First, include the required libraries. The WiFi.h library to connect the ESP32 to the internet (or the ESP8266WiFi.h library for the ESP8266 board) and the Firebase_ESP_Client.h library to interface the boards with Firebase.

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

You also need to include the following for the Firebase library to work.

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

Network Credentials

Include your network credentials in the following lines so that your boards can connect to the internet using your local network.

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Firebase Project API Key and Firebase User

Insert your Firebase project API key—the one you’ve gotten in this section.

#define API_KEY "REPLACE_WITH_YOUR_PROJECT_API_KEY"

Insert the authorized email and the corresponding password—these are the details of the user you’ve added in this section.

// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "REPLACE_WITH_THE_USER_EMAIL"
#define USER_PASSWORD "REPLACE_WITH_THE_USER_PASSWORD"

Firebase Objects and Other Variables

The following line defines a FirebaseData object.

FirebaseData fbdo;

The next line defines a FirebaseAuth object needed for authentication.

FirebaseAuth auth;

Finally, the following line defines FirebaseConfig object needed for configuration data.

FirebaseConfig config;

The uid variable will be used to save the user’s UID. We can get the user’s UID after the authentication.

String uid;

initWiFi()

The initWiFi() function connects your ESP to the internet using the network credentials provided. You must call this function later in the setup() to initialize WiFi.

// Initialize WiFi
void initWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
  Serial.println();
}

setup()

In setup(), initialize the Serial Monitor for debugging purposes at a baud rate of 115200.

Serial.begin(115200);

Call the initWiFi() function to initialize WiFi.

initWiFi();

Assign the API key to the Firebase configuration.

config.api_key = API_KEY;

The following lines assign the email and password to the Firebase authentication object.

auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;

Add the following to the configuration object.

// Assign the callback function for the long running token generation task
config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

// Assign the maximum retry of token generation
config.max_token_generation_retry = 5;

Finally, initialize the Firebase library (authenticate) with the configuration and authentication settings we defined earlier.

// Initialize the library with the Firebase authen and config
Firebase.begin(&config, &auth);

After initializing the library, we can get the user UID by calling auth.token.uid. Getting the user’s UID might take some time, so we add a while loop that waits until we get it.

// Getting the user UID might take a few seconds
Serial.println("Getting User UID");
while ((auth.token.uid) == "") {
  Serial.print('.');
  delay(1000);
}

Finally, we save the user’s UID in the uid variable and print it in the Serial Monitor.

uid = auth.token.uid.c_str();
Serial.print("User UID: ");
Serial.print(uid);

Demonstration

After uploading the code, open the Serial Monitor at a baud rate of 115200.

Note: if you’re using VS Code, you need to add the following line to your platformio.ini file to change the baud rate. Then, save your file.

monitor_speed = 115200

Reset your board by pressing the on-board EN/RST button.

The ESP32/ESP8266 authenticates the user successfully and gets its UID.

ESP32 ESP8266 Firebase Successful Arduino IDE Serial Monitor

Then, go to your Firebase project console to check if it signed in as a user. Go to Authentication > Users. Now you should have the current date in the Signed In field. Additionally, you’ll see that the User UID matches the UID printed by your ESP board in the Serial Monitor.

Firebase Users Last Sign-in

Congratulations! You successfully signed in your ESP32/ESP8266 board as a user. You can combine this example with one of our previous tutorials to send sensor readings to the database as an authorized user: ESP32: Getting Started with Firebase (Realtime Database)

Wrapping Up

In this tutorial, you learned how to set up the ESP32/ESP8266 board as a user that can access your Firebase project with email and password. This was just a simple example that you can apply to more advanced projects.

Setting up the ESP as a user allows you to identify the user to enable or restrict access to the Firebase Project or to the database or to specific database nodes—allows you to set up database rules.

In a future tutorial, we’ll show you how to use this feature to apply database rules and create a web app with login/logout features to authorize and restrict access to the data. Stay tuned.

If you want to learn more about building a fully-featured Firebase Web App to control and monitor your ESP32 and ESP8266 boards from anywhere, take a look at our newest eBook (registrations only available during the next few days):

Other resources that you might find helpful:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

33 thoughts on “ESP32/ESP8266: Firebase Authentication (Email and Password)”

  1. Please create the tutorial for run time wifi credentials addition .it hard to add the wifi password and I’d hard-coded for scalable product

    Reply
  2. Excellent tutorial! Would this solution work for multiple users using the same email address/password? For example, if a user has multiple ESP-32 devices in their home and wanted to connect all of them to the database, can each ESP-32 have the same email/password?

    Reply
  3. Actually just commented with an error but i solved it now it’s okay.
    But now how can we add and fetch data to this specific uid in arduino?

    Reply
  4. thank you for this job,
    i live in rwanda country but our iot technology is very low please how can you help us to develop many company to make many projects for handling or to solve many problems can be solved through iot technology in our country.

    Reply
  5. Hola Sara! como estas! estoy muy satisfecho en haber comprado tu tutorial de inicios con Firebase width Esp8266! Quiero consultarte como hago para agregar mas de un usuario autorizado para poder realizar cambios en el esp8266. En concreto, quiero solo agregar o quitar los usuarios desde la consola firebase , en el codigo que viene en el tutorial solo tiene acceso un solo usuario dentro del codigo del esp8266.
    Saludos ! espero que me puedas guiar !

    Reply
    • Hi.
      To add more users you need to organize the database in a different way and also change the database rules.
      At the moment, I don’t have any tutorials that explain how that works.
      Regards,
      Sara

      Reply
  6. Hi,
    Thanks for this amazing tutorial.
    I have make one firmware wirh this, combined to send water analysis, work 58 minutes, after data transfer is blocked. I have to re login one times once every 58 minutes?
    Thanks in advance

    Reply
  7. Hi sara,
    Thank you for your reply i tried this in loop but i facing error :exit status 1
    ‘FirebaseConfigObj’ was not declared in this scope; did you mean ‘FirebaseConfig’? i tried also (&FirebaseConfig, &auth)

    Reply
  8. Instead of filling in the API_KEY statically, I can set it dynamically so that it can be changed via the app or web, for example.
    Can you suggest me how to do it?

    Reply

Leave a Reply to Sara Santos Cancel reply

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.