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, and get the user UID. 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 when setting up database rules to protect your project’s data.

ESP32 ESP8266 Firebase Authentication Email Password

Updated 30 April 2025.

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

What is Firebase?

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.

Firebase Logo

Project Overview

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

1) Create Firebase Project

Follow the next instructions to create a new project on Firebase.

  1. Go to Firebase and sign in using a Google Account.
  2. Go to the Firebase Console and create a new project.
  3. Give a name to your project, for example: ESP-Project, and click Continue.
    Set Up Firebase Project for ESP32 and ESP8266 Step 1
  4. Next, enable or disable AI assistance for your project. This is optional.
    Set Up Firebase Project for ESP32 and ESP8266 - Enable AI assistant
  5. Disable the option Enable Google Analytics for this project, as it is not needed. Then, click Create project.
    Disable Google Analytics for firebase project
  6. It will take a few seconds to set up your project. Click Continue when it’s ready.
    Firebase Project for ESP32 Ready

  7. You’ll be redirected to your Project console page.
    Firebase console project

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 Build > Authentication and then on Get started.
    Firebase project set authentication
  2. There are several authentication methods like email and password, Google Account, Facebook account, and others.
    SFirebase authentication methods
  3. Select Email/Password and enable that authentication method. Then, click Save.
    Enable Email Password Sign in Firebase
  4. Then, at the top, click on the Users tab. Then, click on Add user.
    Firebase Create a new user
  5. Create a new user with an email and password. The email can be your personal email. Create a password for that user (you need to remember the password later). Finally, click on Add user.
    Firebase add user email and password
  6. The User will show up on the list of users. You can see information about the user, like when it was created, the last time it signed in, and its user UID.
    Firebase User Created

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. To get your project’s API key, on the left sidebar click on Project Settings.
    Firebase Realtime Database Project Settings
  2. Copy the API Key to a safe place because you’ll need it later.
    Firebase Project 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 or ESP8266 using the authorized user email and password.

To program the boards, you can use Arduino IDE, VS Code with the PlatformIO or pioarduino extensions, or other suitable software.

Note: for firebase projects, we recommend using VS Code with the PlatformIO or pioarduino extension because if you want to develop a web application to make the bridge between the ESP 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.

Installing the FirebaseClient Library

To use Firebase with the ESP32 and ESP8266, we’ll use the FirebaseClient library. This library is compatible with the ESP32, ESP8266, and many other boards.

Installation – VS Code + PlatformIO

If you’re using VS Code with the PlatformIO extension, click on the PIO Home icon and then select the Libraries tab. Search for “FirebaseClient“. Select the Firebase Client Library by Mobitz.

Install FirebaseClient Library VS Code

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

Add FirebaseClient Library ro project in 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 FirebaseClient and install the FirebaseClient by Mobitz. We’re using version 2.0.3.
Install Firebase Client Library Arduino IDE

ESP32/ESP8266 Firebase Authentication Email/Password (Get User UID)

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

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at our blog: https://RandomNerdTutorials.com/esp32-esp8266-firebase-authentication/
  Based on this example: https://github.com/mobizt/FirebaseClient/blob/main/examples/App/AppInitialization/UserAuth/UserAuth.ino
*/

#include <Arduino.h>
#if defined(ESP32)
  include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>
#include "ExampleFunctions.h" // Provides the functions used in the examples.

// Network and Firebase credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"

// User functions
void processData(AsyncResult &aResult);

// Authentication
UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);

// Firebase components
FirebaseApp app;
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
AsyncResult dbResult;

bool taskComplete = false;

void setup(){
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)    {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  // Configure SSL client
  ssl_client.setInsecure();
  #if defined(ESP32)
    ssl_client.setConnectionTimeout(1000);
    ssl_client.setHandshakeTimeout(5);
  #elif defined(ESP8266)
    ssl_client.setTimeout(1000); // Set connection timeout
    ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes
  #endif

  // Initialize Firebase
  initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");
}

void loop(){
  // Maintain authentication and async tasks
  app.loop();

  // Check if authentication is ready
  if (app.ready() && !taskComplete){
    taskComplete = true;
    // Print authentication info
    Serial.println("Authentication Information");
    Firebase.printf("User UID: %s\n", app.getUid().c_str());
    Firebase.printf("Auth Token: %s\n", app.getToken().c_str());
    Firebase.printf("Refresh Token: %s\n", app.getRefreshToken().c_str());
    print_token_type(app);
  }
}

void processData(AsyncResult &aResult){
  if (!aResult.isResult())
    return;

  if (aResult.isEvent())
    Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());

  if (aResult.isDebug())
    Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());

  if (aResult.isError())
    Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());

  if (aResult.available())
    Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}

View raw code

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

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), the FirebaseClient.h and WiFiClientSecure libraries to interface the boards with Firebase. We also include the ExampleFunctions.h file which is included in the library that comes with some additional functions for this example.

#include <Arduino.h>
#if defined(ESP32)
    #include <WiFi.h>
#elif defined(ESP8266)
    #include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>
#include "ExampleFunctions.h" // Provides the functions used in the examples.

Defining Credentials

Include your network credentials in the following lines.

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Insert your Firebase project API key.

#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

Set the Firebase email user and corresponding password.

#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"

Declaring Firebase Authentication and Components

The following line creates an authentication object using the project API key, the project user email, and password.

UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);

This creates a FirebaseApp instance called app that refers to the Firebase application.

FirebaseApp app;

The following lines set up the asynchronous communication framework for interacting with Firebase’s Realtime Database. Basically, you create an SSL client using the WiFiClientSecure library. Then, you instantiate an Asynchronous client called aClient that enables secure HTTPS. This will allow you to handle network operations asynchronously.

WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);

setup()

In the setup(), initialize the Serial Monitor and connect the board to your Wi-Fi network.

void setup(){
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)    {
    Serial.print(".");
    delay(300);
  }
  Serial.println();

Configure the SSL Client (different for ESP32 and ESP8266).

// Configure SSL client
ssl_client.setInsecure();
#if defined(ESP32)
  ssl_client.setConnectionTimeout(1000);
  ssl_client.setHandshakeTimeout(5);
#elif defined(ESP8266)
  ssl_client.setTimeout(1000); // Set connection timeout
  ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes
#endif

The following line initializes the Firebase app with authentication and sets the processData() as the callback function for async results (this means that any results from the initializeApp() function will be handled on the processData() callback function).

initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");

loop()

The Firebase library we’re using works asynchronously and with callback functions. This means that when an event happens, the corresponding assigned callback functions will run. To keep the Firebase app running, handling authentication and asynchronous tasks, we need to add app.loop() at the start of our loop() function.

void loop(){
  app.loop();

The app.ready() command checks if Firebase authentication is complete and ready, so that we can proceed with other Firebase operations (like getting the User UID). We also have a control variable taskComplete so that is just runs once to print the user UID.

if (app.ready() && !taskComplete){
  taskComplete = true;

Then, we can get the user UID with app.getUid().

Firebase.printf("User UID: %sn", app.getUid().c_str());

We also print more information about the app auth token.

 Firebase.printf("Auth Token: %sn", app.getToken().c_str());
 Firebase.printf("Refresh Token: %sn", app.getRefreshToken().c_str());
 print_token_type(app);

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 successfully and prints information about the user UID and the authentication token.

ESP32/ESP8266 Get User UID Firebase

Then, go to your Firebase project console to check if it signed in as a user. Go to Authentication > Users. 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) or you can follow this project:

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.

We have a project that shows how to use this feature to create database rules and to build a web app with login/logout features to authorize and restrict access to the data. You can check it out on the following link:

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 eBook:

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!

39 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
  9. Hi, I encountered a weird error…. it logs in normally for the auth but after a while the connection gets refused by firebase. I thought the reason being the token’s expiration, but it keeps saying that the tokes aren’t expired yet.
    Maybe a bug with the library?

    Reply
  10. Good day I am trying to read data from realtime Database in firebase but my code gives permission denied.I am able to authenticate the esp32 and sign it in to firebase and post data to the database my problem is when I try to read data from the database.This is the code block that is supposed to retreive the data.

    I want to retreive the depth from the database .

    Uid
    Devices
    device ID
    -depth

    void getValues()
    {
    if (Firebase.ready())
    {
    if (Firebase.RTDB.getString(&fbdo,uid +”/Devices/” + deviceID + “/depth”))
    {
    if (fbdo.dataType() == “string”)
    {
    depth= fbdo.stringData();
    Serial.println(depth);
    }
    }
    else
    {
    Serial.println(fbdo.errorReason());
    }

    }
    else
    {
    Serial.println(fbdo.errorReason());
    }
    }
    Capture

    Reply

Leave a Comment

Download Our Free eBooks and Resources

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