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.
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.
Project Overview
- Create Firebase Project
- Set Authentication Methods
- Get Project API Key
- 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.
4) Disable the option Enable Google Analytics for this project as it is not needed and click Create project.
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.
2) Select the Option Email/Password.
3) Enable that authentication method and click Save.
4) The authentication with email and password should now be 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.
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.
7) A new user was successfully created and added to the 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.
2) Copy the Web API Key to a safe place because you’ll need it later.
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.
Then, click Add to Project and select the project you’re working on.
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.
- Go to Sketch > Include Library > Manage Libraries
- Search for Firebase ESP Client and install the 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");
}
}
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.
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.
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:
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
Hi.
You can use the WiFi Manager library.
For example: https://github.com/zhouhan0126/WIFIMANAGER-ESP32
Regards,
Sara
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?
Yes.
That is possible.
Regards,
Sara
Hey Sara, great job!
Thank you 🙂
Great work you have done here, but there is 1 issue actually which is:
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
Hi.
What is exactly the error?
What line is highlighted by the error?
Regards,
Sara
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?
Hi.
You can try to combine this example with the following:
– https://randomnerdtutorials.com/esp32-firebase-realtime-database/
You have the retrieved UID, you just need to modify the path where you’ll write to include the UID.
We’ll post a more complete tutorial soon.
Regards,
Sara
Hey Sara, thank you so much i’m actually trying really hard to figure it out how to add and fetch data combining these 2 projects.
Honestly i’m still too fresh on arduino came from flutter programming but however i’m willing to learn so, i hope you could help me with this! it might be simple to you but to me because i’m fresh it will take some guidance at first then everything will be alright.
So if you would help i will appreciate it if you couldn’t then i will wait for the tutorial.
Thaaaaank you so much
Hi.
You can also take a look at this example: https://github.com/mobizt/Firebase-ESP-Client/blob/main/examples/RTDB/Basic/Basic.ino
The tutorial should come out this month or at the beginning of next month.
Regards,
Sara
Have you made the totorial on retrieving the data from database after logging in with email and password
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.
good job 👏 keep up the good work
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 !
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
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
Hi.
Do you get any more information on the serial monitor?
Regards,
Sara
Hi Sara,
Thanks for your reply.
Yes, after 58 minutes Serial monitor show
Failed
Reason: Token is not ready!
Thanks in advance
Hi.
Here’s the same issue: https://github.com/mobizt/Firebase-ESP-Client/discussions/62
I think you need to update your library.
Regards,
Sara
Hi,
Thanks for tutorial.
I am also facing the same problem after 1 hour I tried to control from firebase, esp not responding. serial monitor freeze with lost GPIO message and try to reopen the serial monitor still no response. after hardware rest or repowering, the ESP will work normally, again after 1 hour facing same problem
Hi.
Are you using ESP32 or ESP8266?
Regards,
Sara
I tried on both boards. I am facing the same issue.
Hi.
Try this suggestion from one of our readers:
“Hi, I solved this problem by putting this code in loop, I think maybe there’s a better solution but that works for now, it is because the tokan is expired and nothing is called after than to refresh it
if(Firebase.isTokenExpired())
Firebase.refreshToken(&FirebaseConfigObj);
“
Hi!
I have solved with this lines:
https://github.com/mobizt/Firebase-ESP-Client/blob/60680080caf053db16106f63b20df1163324527b/examples/RTDB/Basic/Basic.ino#L144-L149
Hi,
Thank you, i already found this solution. But when i try to combine those codes (this and that) i am facing error. Can you help with that?
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)
Try
(&config, &auth)
Hi,
Thank you, Error: no matching function for call to ‘Firebase_ESP_Client::refreshToken(FirebaseConfig*, FirebaseAuth*)’
Hi Sara,
After a long research I found a solution, but I facing error can you plz help with that.
https://github.com/mobizt/Firebase-ESP-Client/blob/60680080caf053db16106f63b20df1163324527b/examples/RTDB/Basic/Basic.ino#L144-L149
https://create.arduino.cc/projecthub/embeddedlab786/iot-and-manual-switch-control-home-appliances-using-firebase-c90418
Hi.
Add something like this in the loop():
if firebase.ready()
return
Regards,
Sara
Hi Sara,
Thank you for your reply. After a long search finally found a solution and tested also(after 10 days still running with no issue)
loop()
if(Firebase.isTokenExpired())
firebase.ready()
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?
How can we achieve this with any sim module?
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?
Anyone who’ve done this using SIM800 or similar?
Thanks it workes great can you please help with retreiving data from the realtime Database with the authentication?
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