Movatterモバイル変換


[0]ホーム

URL:


Skip to content
HOMEESP32ESP8266ESP32-CAMRASPBERRY PIMICROPYTHONRPi PICOARDUINOREVIEWS

ESP32/ESP8266 Web Server HTTP Authentication (Username and Password Protected)

Learn how to add HTTP authentication with username and password to your ESP32 and ESP8266 NodeMCU web server projects using Arduino IDE. You can only access your web server if you type the correct user and pass. If you logout, you can only access again if you enter the right credentials.

The method we’ll use can be applied to web servers built using the ESPAsyncWebServer library.

ESP32 ESP8266 NodeMCU Web Server HTTP Authentication Username and Password Protected Arduino IDE

The ESP32/ESP8266 boards will be programmed using Arduino IDE. So make sure you have these boards installed:

Security Concerns

This project is meant to be used in your local network to protect from anyone just typing the ESP IP address and accessing the web server (like unauthorized family member or friend).

If your network is properly secured, running an HTTP server with basic authentication is enough for most applications. If someone has managed to hack your network, it doesn’t matter if you use HTTP or HTTPS. The hacker can bypass HTTPS and get your user/pass.

Project Overview

Let’s take a quick look at the features of the project we’ll build.

ESP32 ESP8266 NodeMCU Password Protected Web Server Project Overview
  • In this tutorial you’ll learn how to password protect your web server;
  • When you try to access the web server page on the ESP IP address, a window pops up asking for a username and password;
  • To get access to the web server page, you need to enter the right username and password (defined in the ESP32/ESP8266 sketch);
  • There’s a logout button on the web server. If you click the logout button, you’ll be redirected to a logout page. Then, close all web browser tabs to complete the logout process;
  • You can only access the web server again if you login with the right credentials;
  • If you try to access the web server from a different device (on the local network) you also need to login with the right credentials (even if you have a successful login on another device);
  • The authentication is not encrypted.

Note: this project was tested on Google Chrome and Firefox web browsers and Android devices.

Installing Libraries – Async Web Server

To build the web server you need to install the following libraries:

You can install those libraries in the Arduino IDE Library Manager. Go toSketch>Include Library >Manage Libraries and search for the libraries’ names.

Web Server Code with Authentication

Copy the following code to your Arduino IDE.

/*********  Rui Santos & Sara Santos - Random Nerd Tutorials  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-web-server-http-authentication/  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.*********/// Import required libraries#ifdef ESP32  #include <WiFi.h>  #include <AsyncTCP.h>#else  #include <ESP8266WiFi.h>  #include <ESPAsyncTCP.h>#endif#include <ESPAsyncWebServer.h>// Replace with your network credentialsconst char* ssid = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";const char* http_username = "admin";const char* http_password = "admin";const char* PARAM_INPUT_1 = "state";const int output = 2;// Create AsyncWebServer object on port 80AsyncWebServer server(80);const char index_html[] PROGMEM = R"rawliteral(<!DOCTYPE HTML><html><head>  <title>ESP Web Server</title>  <meta name="viewport" content="width=device-width, initial-scale=1">  <style>    html {font-family: Arial; display: inline-block; text-align: center;}    h2 {font-size: 2.6rem;}    body {max-width: 600px; margin:0px auto; padding-bottom: 10px;}    .switch {position: relative; display: inline-block; width: 120px; height: 68px}     .switch input {display: none}    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}    input:checked+.slider {background-color: #2196F3}    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}  </style></head><body>  <h2>ESP Web Server</h2>  <button onclick="logoutButton()">Logout</button>  <p>Ouput - GPIO 2 - State <span id="state">%STATE%</span></p>  %BUTTONPLACEHOLDER%<script>function toggleCheckbox(element) {  var xhr = new XMLHttpRequest();  if(element.checked){     xhr.open("GET", "/update?state=1", true);     document.getElementById("state").innerHTML = "ON";    }  else {     xhr.open("GET", "/update?state=0", true);     document.getElementById("state").innerHTML = "OFF";        }  xhr.send();}function logoutButton() {  var xhr = new XMLHttpRequest();  xhr.open("GET", "/logout", true);  xhr.send();  setTimeout(function(){ window.open("/logged-out","_self"); }, 1000);}</script></body></html>)rawliteral";const char logout_html[] PROGMEM = R"rawliteral(<!DOCTYPE HTML><html><head>  <meta name="viewport" content="width=device-width, initial-scale=1"></head><body>  <p>Logged out or <a href="/">return to homepage</a>.</p>  <p><strong>Note:</strong> close all web browser tabs to complete the logout process.</p></body></html>)rawliteral";// Replaces placeholder with button section in your web pageString processor(const String& var){  //Serial.println(var);  if(var == "BUTTONPLACEHOLDER"){    String buttons ="";    String outputStateValue = outputState();    buttons+= "<p><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"output\" " + outputStateValue + "><span class=\"slider\"></span></label></p>";    return buttons;  }  if (var == "STATE"){    if(digitalRead(output)){      return "ON";    }    else {      return "OFF";    }  }  return String();}String outputState(){  if(digitalRead(output)){    return "checked";  }  else {    return "";  }  return "";}void setup(){  // Serial port for debugging purposes  Serial.begin(115200);  pinMode(output, OUTPUT);  digitalWrite(output, LOW);    // Connect to Wi-Fi  WiFi.begin(ssid, password);  while (WiFi.status() != WL_CONNECTED) {    delay(1000);    Serial.println("Connecting to WiFi..");  }  // Print ESP Local IP Address  Serial.println(WiFi.localIP());  // Route for root / web page  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){    if(!request->authenticate(http_username, http_password))      return request->requestAuthentication();    request->send(200, "text/html", index_html, processor);  });      server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request){    request->send(401);  });  server.on("/logged-out", HTTP_GET, [](AsyncWebServerRequest *request){    request->send(200, "text/html", logout_html, processor);  });  // Send a GET request to <ESP_IP>/update?state=<inputMessage>  server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {    if(!request->authenticate(http_username, http_password))      return request->requestAuthentication();    String inputMessage;    String inputParam;    // GET input1 value on <ESP_IP>/update?state=<inputMessage>    if (request->hasParam(PARAM_INPUT_1)) {      inputMessage = request->getParam(PARAM_INPUT_1)->value();      inputParam = PARAM_INPUT_1;      digitalWrite(output, inputMessage.toInt());    }    else {      inputMessage = "No message sent";      inputParam = "none";    }    Serial.println(inputMessage);    request->send(200, "text/plain", "OK");  });    // Start server  server.begin();}  void loop() {  }

View raw code

You just need to enter your network credentials (SSID and password) and the web server will work straight away. The code is compatible with both theESP32 andESP8266 boards.

As an example, we’re building a web server that controlsGPIO 2. You can use the HTTP authentication with any web server built with theESPAsyncWebServer library.

How the Code Works

We’ve already explained in great details how web servers like this work in previous tutorials (DHT Temperature Web Server orRelay Web Server), so we’ll just take a look at the relevant parts to add username and password authentication to the web server.

Network Credentials

As mentioned previously, you need to insert your network credentials in the following lines:

const char* ssid = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting Your Username and Password

In the following variables set the username and password for your web server. By default, the username isadmin and the password is alsoadmin. We definitely recommend to change them.

const char* http_username = "admin";const char* http_password = "admin";

Logout Button

In theindex_html variable you should add some HTML text to add a logout button. In this example, it’s a simple logout button without styling to make things simpler.

<button>Logout</button>

When clicked, the button calls thelogoutButton() JavaScript function. This function makes an HTTP GET request to your ESP32/ESP8266 on the/logout URL. Then, in the ESP code, you should handle what happens after receiving this request.

function logoutButton() {  var xhr = new XMLHttpRequest();  xhr.open("GET", "logout", true);  xhr.send();

One second after you click the logout button, you are redirected to the logout page on the/logged-out URL.

  setTimeout(function(){ window.open("/logged-out","_self"); }, 1000);}

Handle Requests with Authentication

Every time you make a request to the ESP32 or ESP8266 to access the web server, it will check whether you’ve already entered the correct username and password to authenticate.

Basically, to add authentication to your web server, you just need to add the following lines after each request:

if(!request->authenticate(http_username, http_password))    return request->requestAuthentication();

These lines continuously pop up the authentication window until you insert the right credentials.

You need to do this for all requests. This way, you ensure that you’ll only get responses if you are logged in.

For example, when you try to access the root URL (ESP IP address), you add the previous two lines before sending the page. If you enter the wrong credentials, the browser will keep asking for them.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){  if(!request->authenticate(http_username, http_password))    return request->requestAuthentication();  request->send_P(200, "text/html", index_html, processor);});

Here’s another example for when the ESP receives a request on the/state URL.

server.on("/state", HTTP_GET, [] (AsyncWebServerRequest *request) {  if(!request->authenticate(http_username, http_password))    return request->requestAuthentication();  request->send(200, "text/plain", String(digitalRead(output)).c_str());});

Handle Logout Button

When you click the logout button, the ESP receives a request on the/logout URL. When that happens send the response code 401.

server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request){  request->send(401);});

The response code 401 is an unauthorized error HTTP response status code indicating that the request sent by the client could not be authenticated. So, it will have the same effect as a logout – it will ask for the username and password and won’t let you access the web server again until you login.

When you click the web server logout button, after one second, the ESP receives another request on the/logged-out URL. When that happens, send the HTML text to build the logout page (logout_html variable).

server.on("/logged-out", HTTP_GET, [](AsyncWebServerRequest *request){  request->send_P(200, "text/html", logout_html, processor);});

Demonstration

Upload the code to your ESP32 or ESP8266 board. Then, open the Serial Monitor and press the on-board RST/EN button to get is IP address.

Open a browser in your local network and type the ESP IP address.

The following page should load asking for the username and password. Enter the username and password and you should get access to the web server. If you haven’t modified the code, the username isadminand the password isadmin.

ESP32 ESP8266 NodeMCU Web Server HTTP Authentication type Username and Password

After typing the right username and password, you should get access to the web server.

ESP32 ESP8266 NodeMCU Web Server HTTP Auth Username and Password Protected

You can play with the web server and see that it actually controls the ESP32 or ESP8266 on-board LED.

ESP32 board Built in LED turned on HIGH

In the web server page, there’s a logout button. If you click that button, you’ll be redirected to a logout page as shown below.

If you click the “return to homepage” link, you’ll be redirected to the main web server page.

If you’re using Google Chrome, you’ll need to enter the username and password to access the web server again.

If you’re using Firefox, you need to close all web browser tabs to completely logout. Otherwise, if you go back to the main web server page, you’ll still have access.

So, we advise that you close all web browser tabs after clicking the logout button.

You also need to enter the username and password if you try to get access using a different device on the local network, even though you have access on another device.

ESP32 ESP8266 NodeMCU Web Server HTTP Authentication Username and Password Protected Arduino IDE Demonstration

Wrapping Up

In this tutorial, you’ve learned how to add authentication to your ESP32 and ESP8266 web servers (password protected web server). You can apply what you learned in this tutorial to any web server built with the ESPAsyncWebServer library.

We hope you’ve found this tutorial useful. Other web server projects you may like:

Learn more about the ESP32 and ESP8266 boards with our resources:

Thanks for reading.



SMART HOME with Raspberry Pi ESP32 and ESP8266 Node-RED InfluxDB eBook
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 »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects »Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

81 thoughts on “ESP32/ESP8266 Web Server HTTP Authentication (Username and Password Protected)”

  1. Again, nice tutorial. Works fine, but need more explanation on the controlling of GPIO 2.
    I’m confused on how that part works. Since a NodeMCU is backwards with the LED, tried to make it look correct, but really got messed up.

    Reply
  2. good afternoon,
    LOGOUT button (esp32) does not work

    Reply
  3. Hello,

    Nice tutorial like always :p
    Also possible to do or to add https instead of http?

    Regards

    Reply
  4. Good Afternoon,
    I have the same error with the Logout-Button (no reaction, no login window).

    Kind Regards
    Juergen B.

    Reply
    • Hi.
      It works fine on our end. However, we’re currently trying to solve the problem and we’ll update the tutorial when it is solved.
      Regards,
      Sara

      Reply
      • Boa tarde Sara.
        Bom funciona tudo menos botão LOGOUT, não faz nada, parece que não gera o 401.
        Fico muito grato pela pronta resposta.
        Beiral

        OIII Sara
        voltei a carregar o exemplo e funcionou diferente. agora ele sai da pagina porem se vc pedir para entrar ele não pede a autenticação

        “Logged out or return to homepage.

        Note: close all web browser tabs to complete the logout process.
        ok, fico grato por informações
        Beiral

        Reply
      • hi Sara can you help me please. i upload the code no problem at all. but the serial monitor is always connecting to wifi. i cant find also the wifi credential can you help me how? thank in advance love your project.

        Reply
  5. Good Afternoon,
    My solution:
    server.on(“/logout”, HTTP_GET, [](AsyncWebServerRequest *request){
    //request->send(401);
    return request->requestAuthentication();
    });
    Would that be okay?
    Kind Regards
    Juergen B.

    Reply
  6. what is the command line to authenticate automatically the admin & password?

    Reply
    • Hello Paulo. In the past, you could type in the browser URL bar:http://admin:[email protected]

      However, that methodno longer works.

      Reply
      • Como posso adicionar outro user ao programa? Tentei assim e não consigo autenticar

        const char* http_username = “admin”;
        const char* http_password = “admin”;

        const char* user1 = “arroz”;
        const char* user1_password = “arroz”;

        server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request)
        {
        Serial.println(request->authenticate(http_username, http_password));
        if(!request->authenticate(user1, user1_password))
        return request->requestAuthentication();
        if(!request->authenticate(http_username, http_password) || !request->authenticate(user1, user1_password))
        return request->requestAuthentication();

        server.on(“/update”, HTTP_GET, [] (AsyncWebServerRequest *request) {
        if(!request->authenticate(http_username, http_password) || !request->authenticate(user1, user1_password))
        return request->requestAuthentication();

        Reply
      • Boa Tarde !, Rui como seria o caso inverso disso ? , ex : consumir uma API web que precise autenticar . Ao invés de conexão com ESP32 o próprio se conectar em uma API web .

        Reply
  7. Hi Sara
    Very good tutorial. I am fan of of random nerd tutorials. The tutorials are very
    well explained. I request you to add a wi-fi manager so the wifi credentials
    hard coding can be avoided.

    Regards
    Harnam

    Reply
  8. Can you also do this on micropython? Thank you.

    Reply
  9. Hi,
    Thanks for great tutorials.
    how can I add second button to control another device.

    thanks for great Job.

    Junaid

    Reply
  10. Hi people, im daniel from colombia, its exciting, i made this application 3 months ago and i would like to know if it is possible to do it with an https server ?, i was following this tutorial youtube.com/watch?v=Wm1xKj4bKsY and i achieve to implement the https server. but i did not succeed in implementing the authentication, greetings to all and thank you very much in advance

    Reply
  11. Hi! Thanks for a cool tutorial. For anyone trying this. When using ASYNCTCP and webservers you can not add delay. Instead of that you should “manage” your relay buttons in the loop() function and make an constant state.
    void loop() {
    if(doorState == 1){
    Serial.println(“opa”);
    digitalWrite(5, 1);
    delay(3000);
    digitalWrite(5, 0);
    doorState = 0;
    Serial.println(“opa baiges”);
    }
    }

    And instead of doing digitalWrite(pin, inputMassage.toInt())
    you would do
    doorState = inputMassage.toInt()
    Then it would trigger the relay in the loop() function.

    Reply
  12. Hi!.. nice tutorial. can i add a program so that when i access the ESP 32/8266 web server i could change the username and password so the next time you access the Authentication you input the new username and password? Thanks in advance!.

    Reply
    • Hi.
      Yes, you can do that.
      You need to create a page with an HTML form that updates the username and password variables and saves them in SPIFFS, for example.
      You can take a look at this tutorial that might help:https://randomnerdtutorials.com/esp32-esp8266-input-data-html-form/
      Regards,
      Sara

      Reply
      • Hi Sara!
        Thanks for replying.. so i still need to program/create a button just like the “Log Out” button already in the program so that it can go the HTML form that updates the username and password? .. sorry, im a newbee.. hope you could share a sketch on how i can incorporate the two (authenticated web server and the html form to change username and password).. thanks again in advance.. 🙂

        Reply
  13. Olá mais uma ves um ótimo post meus parabéns , mas ao invés de criar uma pagina assincrona no espteria como puxar a pagina do spiffs.
    Obrigado !

    Reply
  14. ESP32/ESP8266 Web Server HTTP Authentication (Username and Password ProtectedHello,
    I created a project on ESP8266 with your arduino sketch and it works fine and thank you for it. However, I believe the program does not quite match the photos. Indeed, we can see the return of the state of the relay, while on my order web page there is no state displayed. Could you please correct this flaw? Being a beginner in this field, I failed to get it. On the other hand I managed to add a second channel and it works well. I thank you in advance. Cordially. Jean Yves

    Reply
    • Hi.
      You are right.
      I’m sorry about that.
      I didn’t notice that those lines were missing.
      The code is now updated and should work as expected.
      Regards,
      Sara

      Reply
      • Hello Sara,
        Thank you for correcting the program. I have tested this program but still get a compilation error. (Compilation error for the Generic ESP8266 Module board).
        I tried to change ESP8266 version card: 2.5.1 – 2.5.2 – 2.6.0 – 2.6.1 – 2.6.2 – 2.7.4. Always a card error.
        Question: Which ESP8266 card should I install?
        Thank you for your help. Best regards,
        Jean Yves

        Otherwise, here is the result after compilation:

        In file included from /Users/admin/Documents/Arduino/Serveur_1OUT_AURHENTIF_STATE/Serveur_1OUT_AURHENTIF_STATE.ino:15:0:
        /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/ESP8266WiFi.h: In function ‘void setup ()’:
        /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/ESP8266WiFi.h:27:8: error: expected unqualified-id before string constant
        extern “C” {
        ^
        In file included from /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/WiFiClientSecure.h:41:0,
        from /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/WiFiServerSecure.h:20,
        from /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/ESP8266WiFi.h:41,
        from /Users/admin/Documents/Arduino/Serveur_1OUT_AURHENTIF_STATE/Serveur_1OUT_AURHENTIF_STATE.ino:15:
        /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.h:148:28: error: expected ‘}’ before end of line
        #pragma GCC diagnostic push
        ^
        /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.h: At global scope:
        /Users/admin/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.1/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.h:148:28: error: expected declaration before end of line
        exit status 1
        Compilation error for the Generic ESP8266 Module board

        Reply
  15. Greetings dear SARA SANTOS could you help me I have a question how could I place a second button without losing security but I can not do it I tried everything but I can not place it, please help me since this is the basis of my thesis I will wait for your prompt response . greetings from Ecuador

    saludos querida SARA SANTOS me podria ayudar tengo una pregunta como podria colocar un segundo boton sin perder la seguridad pero no puedo lo puedo realizar lo intentado de todo pero no logro colocarlo, ayudeme porfavor ya que esta es la base de mi tesis esperare su pronta respuesta . saludos desde ecuador

    Reply
  16. feedback : Good job .

    Reply
  17. Hi
    Thanks for this nice post.it works fine for ESP8266-01.i want define GPIO-0 how can i add second on-off button to web page?
    thanks in advance

    Reply
  18. Hello
    please, how can i change : request->send_P(200, “text/html”, index_html, processor); when i have index.html and logout.html codes ans js codes in different foldes ?

    thank you

    Reply
  19. Como posso adicionar mais 1 utilizador?
    Fiz assim mas não consigo logar com nenhum:

    const char* http_username = “admin”;
    const char* http_password = “admin”;

    const char* user1 = “arroz”;
    const char* user1_password = “arroz”;

    server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){
    if(!request->authenticate(http_username, http_password) || !request->authenticate(user1, user1_password))
    return request->requestAuthentication();

    server.on(“/update”, HTTP_GET, [] (AsyncWebServerRequest *request) {
    if(!request->authenticate(http_username, http_password) || !request->authenticate(user1, user1_password))
    return request->requestAuthentication();

    Reply
  20. Hey,

    Very nice tutorial as always!
    Is there a possibility to change the style of the login?

    Thank you for any help in advance!

    Regards,
    Immanuel

    Reply
  21. Hi! I tried to use your example and get this errors: “Uncaught ReferenceError: logoutButton is not defined” and “Uncaught ReferenceError: toggleCheckbox is not defined”, logout button and check box dont work

    Reply
  22. Hi there
    i tried your project and i got this error “AsyncTCP.h: No such file or directory
    ” so where can i find AsyncTCP.h file.thanks

    Reply
    • Hi
      Click the following link to download the library:https://github.com/me-no-dev/AsyncTCP/archive/refs/heads/master.zip
      In the Arduino IDE, go to Sketch > Include Library > Add ZIP library.
      Regards,
      Sara

      Reply
      • i have problems while changing the username and password on webpage.
        can you please help me ?
        when i define global values out of setup()
        i can use them in this form :
        server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request) {
        if(!request->authenticate(hUsername, hPassword)){
        return request->requestAuthentication();
        }
        Serial.println(“root /index.html should be here!!”);
        });

        but when my user decide to change those usernames and pass
        the program returns wrong value : and then crashes
        .
        excuse me for my poor english .

        Reply
  23. Hi, is it able to have multiple usernames & passwords for the http authentication?

    Reply
    • Yes, try this

      if (!request->authenticate(http_username, http_password))
      {

      if (!request->authenticate(http_username2, http_password2))
      {
      Serial.println("İkinci if");
      return request->requestAuthentication();
      }
      }

      Reply
  24. Was having a hard time for the logout for ESP8266. There was no documentation to do it, you did great thanks!

    Reply
  25. Hello, How are you?
    I just want to know how can I login to wifi network using esp32, there are a lot of networks that needs to login before access to the internet, how can I login using esp32. Thank you?

    Reply
  26. Hello, I am new to programming and this my first time I visit this quote
    I would like to use a wifi manager and have an authentication page
    And use my esp 8266 in wifi repeater mode and have access to my esp8266 even if it is not connected to any network I do not want it to be able to restart if it has missed or c connected

    Reply
  27. Sara,
    everything works great, but I couldn’t get more buttons…
    Could you make it work with an option for more buttons?

    Reply
  28. Hi, in the projects “ESP32-CAM Car Robot” you use the library “esp_http_server.h” instead of “ESPAsyncWebServer.h”
    How can i use Authentication with esp_http_server.h ?
    Thank you so much.

    Reply
  29. I am wondering how all this could be done if I had all the files (index.html, style.css for the root webpage(index.html) and logout.html) in SPIFFS inside the folder “data”.

    The line: Logout would be inside index.html file? and inside the script tags of this html file would be the definition of the logoutButton function? here in this function xhr is used, how that can be changed so as not having xhr but only SSE events inside my sketch?

    we would have inside sketch something like that: (??)

    // Route for root / web page
    server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request) {
    if(!request->authenticate(http_username, http_password))
    return request->requestAuthentication();
    request->send(SPIFFS, “/index.html”, “text/html”);
    });

    // Route to load style.css file
    server.on(“/style.css”, HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(SPIFFS, “/style.css”, “text/css”);
    });

    server.on(“/logout”, HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(401);
    });

    server.on(“/logged-out”, HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, “logout.html”, “text/html”);
    });

    Reply
  30. Hello Sara,

    With an ESP8266-01, I would like to carry out a circuit allowing the switching of an output (for example activating a relay) and an entry of detection of an event (for the opening of a door) with an authentication by words of pass. I failed to achieve this. However, I made and modified two of your sketches.
    1- Sketche for the web server with password authentication that I modified in two outputs.
    2- Sketche to warn via Telegram when a door is open, I changed it for two doors and it works perfectly.

    With these two sketches, I wanted to transform them to have an output order (relay) and an entry (door detection) with password for the internet all via Telegram. But I can’t do it, and I have mistakes. I didn’t find this sketche on your presentation Internet page but maybe you have it somewhere? If not, do you think of such an achievement soon? With my thanks for your answer. Best regards. Jean Yves

    Reply
  31. Hello Sara,
    I love your nice tutorials. They helped me a much getting started with ESPs.

    I have the same problems logging out like others befor. It seems that it doesn’t work. I found out that you need to close the whole browser, closing only the website-tab from the tabbar is not enough.
    Anyway, I browse a bit about logging out from a simple HTTP connection and it looks like I found a way to do.

    xhr.open(“GET”, “/logout”, true, “log”, “out”);

    I simply open the XMLHttpRequest() with a “dummy login” (User=”log”, Password=”out”). The connection is now authorized with this new dumm login.

    If you then try to open the “/” page (also works in the same tab) the “request->authenticate(http_username, http_password))” returns “false” and you will be asked for the correct login.

    Thanks a lot,
    Dominik

    Reply
  32. CODE NOT WORKING

    Reply
  33. Hi, what a wonderful tutorials those ones you make, thank you so mucho for all of them.

    I need to ask you something about it: I’m working on an applicatio that in certain cases updates one page at a regular intervals and because of that every time the page is updated it ask me to load again the credentials but, the authentication emerging window doesn’t shows the checkbox to allow the browser to remember the user and password, just like the authentication window you showed. How can I make the browser to allow remember the user and password?. Thanks in advance for the help.

    Reply
  34. Hi, testing the login/logout code in February 2025 in the latest version of well-known browsers, using Dominik’s (see above) suggestion of a dummy login (which defintiely makes it better but doesn’t solve all problems)

    Firefox/Librewolf : behaviour as exptected: logout actually logs you out and clicking ‘return to homepage’ requires you to enter credentials again

    Chrome/Opera/Edge : code NOT working, clicking ‘return to homepage’ immediately logs you in again using the credentials that worked, DESPITE using the dummy credentials “log”/”out”. Even closing the tab makes NO difference.

    Please revisit this problem and offer a solution that works with current browsers.

    Reply
  35. Hi Sara,

    I am using the following:

    esp32 core 3.0.7
    ESPAsyncWebSrv 1.2.9 by dvarrel

    I just tested again and Firefox/LibreWolf works as expected. Chrome/Opera/Edge fail.

    When I visit my page I am prompted for username/pwd, I supply these and I get to see the page. On this (configuration) page there are some buttons, clicking them will get my ESP to do something eg light an LED. So far so good.

    When I logout of the page (I have a button for that) I get the “Logged out. Return to homepage. Note: close all web browser tabs to complete the logout process.” page. Now if I click the back arrow in my Chrome/Opera/Edge browser I get back to the configuration page and clicking one of the buttons STILL gets the ESP to perform the action!

    When I do the same in FireFox/LibreWolf I also still get to see the configuration page but as soon as I click a button I am prompted for username/pwd again (as it should).

    If after logging out I click ‘Return to homepage’ then in Chrome/Opera/Edge I immediately get to the page again (as if I never logged out), in Firefox/LibreWolf I need to enter username/pwd again.

    I made sure there were no other tabs open. It looks liks every browser based on Chromium has some caching mechanism that does not respect the logout.

    Reply
  36. Hi Sara,

    I have done some testing using the very code of the project above and have reached the following conclusion, for you to verify:

    In function logoutButton:

    xhr.open(“GET”, “/logout”, true); -> code WORKS in Chromium based browsers, code FAILS in Firefox

    if I change it (Dominik’s suggestion above) to:

    xhr.open(“GET”, “/logout”, true, “log”, “out”); -> code FAILS in Chromium based browsers, code WORKS in Firefox

    I don’t understand the mechanism behind this. The problem is that there seems to be NO way to get it to work in ALL browers (Chromium based AND Firefox).

    The temporary solution I have is this change to your code:

    Logout Chromium
    Logout Firefox

    function logoutButton() {
    var xhr = new XMLHttpRequest();
    xhr.open(“GET”, “/logout”, true);
    xhr.send();
    setTimeout(function(){ window.open(“/logged-out”,”_self”); }, 1000);
    }
    function logoutButtonFF() {
    var xhr = new XMLHttpRequest();
    xhr.open(“GET”, “/logout”, true, “log”, “out”);
    xhr.send();
    setTimeout(function(){ window.open(“/logged-out”,”_self”); }, 1000);
    }

    Can you please investigate and confirm this and if possible come up with a solution?

    Kind regards,

    edwinov

    Reply
  37. My post above failed to correctly display some code but I added a SECOND button with onclick = “logoutButtonFF()”.

    Reply
  38. Hi Sara,

    Thanks for your reply.

    I am now using the exact libraries you link to:

    Version 3.7.2 ofhttps://github.com/ESP32Async/ESPAsyncWebServer
    Version 3.3.8 ofhttps://github.com/ESP32Async/AsyncTCP

    And STILL the same problem.

    Chrome works fine. Firefox not. In Firefox even closing the tab does not make a difference, when visiting the page again I do not have to log in and can still access the slider.

    Again, using

    xhr.open(“GET”, “/logout”, true, “log”, “out”);

    instead of

    xhr.open(“GET”, “/logout”, true);

    reverses everything: Chrome fails and Firefox works.

    Please at least install Firefox and see for yourself.

    There has to be some solution that works on all browsers.

    Kind regards,

    edwinov

    Reply
  39. Hi Sara,

    Has my previous comment been deleted?

    I posted that I am now using the exact versions you refer to:

    v3.7.6. of ESP32Async/ESPAsyncWebServer
    v3.3.8 of ESP32Async/AsyncTCP

    And that I STILL have the same problem.

    xhr.open(“GET”, “/logout”, true); -> works on Chrome, fails on Firefox
    xhr.open(“GET”, “/logout”, true ,”foo”, “bar”); -> fails on Chrome, works on Firefox

    Surely there has to be a way to make it work on both.

    Kind regards,

    edwinov

    Reply
    • Hi.
      No. Your comment was not deleted.
      We don’t delete comments unless they are inappropriate.

      It seems that issue is related to the way Firefox handles the logout. It caches the credentials. So, to logo out, what you’re doing is sending a wrong username and password, which works. I think this comment explains pretty well what is happening:https://github.com/arangodb/arangodb/issues/688#issuecomment-37061076

      I tried two new different methods, include the one you’re suggesting. I couldn’t find a way to make it work on both chrome and Firefox.
      In Firefox, if you logout and close the web browser window, when yo try to access again, it will ask for the credentials again.
      So, I guess this is a limitation. Make sure to close the web browser window, after logging out.

      Regards,
      Sara

      Reply

Leave a CommentCancel reply

Learn ESP32

ESP32 Introduction

ESP32 Arduino IDE

ESP32 Arduino IDE 2.0

VS Code and PlatformIO

ESP32 Pinout

ESP32 Inputs Outputs

ESP32 PWM

ESP32 Analog Inputs

ESP32 Interrupts Timers

ESP32 Deep Sleep

Protocols

ESP32 Web Server

ESP32 LoRa

ESP32 BLE

ESP32 BLE Client-Server

ESP32 Bluetooth

ESP32 MQTT

ESP32 ESP-NOW

ESP32 Wi-Fi

ESP32 WebSocket

ESP32 ESP-MESH

ESP32 Email

ESP32 Text Messages

ESP32 HTTP GET POST

HTTP GET Web APIs

HTTP POST Web APIs

Server-Sent Events

Web Servers

Output Web Server

PWM Slider Web Server

PWM Multiple Sliders Web Server

Async Web Server

Relay Web Server

Servo Web Server

DHT Web Server

BME280 Web Server

BME680 Web Server

DS18B20 Web Server

LoRa Web Server

Plot/Chart Web Server

Chart Multiple Series Web Server

SPIFFS Web Server

Thermostat Web Server

Momentary Switch Web Server

Physical Button Web Server

Input Fields Web Server

Images Web Server

RGB LED Web Server

Timer/Pulse Web Server

HTTP Auth Web Server

MPU-6050 Web Server

MicroSD Card Web Server

Stepper Motor Web Server

Stepper Motor WebSocket

Gauges Web Server

DIY Cloud

ESP32 Weather Station

Control GPIOs

View Sensor Readings

ESP32 MySQL

ESP32 PHP Email

ESP32 SIM800L

Cloud Node-RED Dashboard

Cloud MQTT Broker

ESP32 Cloud MQTT

ESP-NOW

ESP-NOW Introduction

ESP-NOW Two-Way

ESP-NOW One-to-Many

ESP-NOW Many-to-One

ESP-NOW + Wi-Fi Web Server

Firebase

Firebase Realtime Database

Firebase Web App

Firebase Authentication

Firebase BME280

Firebase Web App Sensor Readings

Firebase ESP32 Data Logging

Modules

ESP32 Relay Module

ESP32 DC Motors

ESP32 Servo

ESP32 Stepper Motor

ESP32 MicroSD Card

ESP32 MicroSD Card Data Logging

ESP32 PIR

ESP32 HC-SR04

ESP32 I2C Multiplexer

Sensors

ESP32 DHT11/DHT22

ESP32 BME280

ESP32 BME680

ESP32 DS18B20

ESP32 Multiple DS18B20

ESP32 BMP180

ESP32 BMP388

MQTT DHT11/DHT22

MQTT BME280

MQTT BME680

MQTT DS18B20

ESP32 MPU-6050

Displays

ESP32 OLED

ESP32 LCD

OLED Temperature

ESP32 Features

ESP32 Hall Sensor

ESP32 Touch Sensor

ESP32 I2C

ESP32 Flash Memory

ESP32 Dual Core

Useful Guides

ESP32 Troubleshooting

ESP32 Access Point

ESP32 Fixed IP Address

ESP32 MAC Address

ESP32 Hostname

ESP32 OTA

ESP32 OTA Arduino

ESP32 OTA VS Code

ESP32 Solar Panels

ESP32 Alexa

ESP32 Install SPIFFS

ESP32 Time and Date

ESP32 Epoch Time

ESP32 Google Sheets

ESP32 Email Altert

ESP32 ThingSpeak

Weather Station Shield

ESP32 IoT Shield

ESP32 Weather Station PCB

ESP32 Wi-Fi Manager

VS Code and PlatformIO

VS Code SPIFFS

VS Code Workspaces

Save Data Preferences Library

Reconnect to Wi-Fi

Useful Wi-Fi Functions

Other Projects

Telegram Control Outputs

Telegram Sensor Readings

Telegram Detect Motion

Telegram Group

ESP32 Status PCB

ESP32 BMP388 Datalogger

ESP32 Web Serial

ESP32 Door Monitor

ESP32 Door Telegram

ESP32 NTP Timezones

ESP32 Boards

ESP32 Camera

ESP32 LoRa

ESP32 OLED

ESP32 SIM800L

Learn More

Learn ESP32

Learn ESP8266

Learn ESP32-CAM

Learn MicroPython

Learn Arduino

Build Web Servers eBook

Smart Home eBook

Firebase Web App eBook

ESP32 Premium Course

Affiliate Disclosure:Random Nerd Tutorials is a participant in affiliate advertising programs designed to provide a means for us to earn fees by linking to Amazon, eBay, AliExpress, and other sites. We might be compensated for referring traffic and business to these companies.



Learn ESP32 with Arduino IDE eBook » Complete guide to program the ESP32 with Arduino IDE!



SMART HOME with Raspberry Pi, ESP32, and ESP8266 » learn how to build a complete home automation system.



Learn Raspberry Pi Pico/Pico W with MicroPython​ » The complete getting started guide to get the most out of the the Raspberry Pi Pico/Pico W (RP2040) microcontroller board using MicroPython programming language.



🔥 Learn LVGL: Build GUIs for ESP32 Projects​ » Learn how to build Graphical User Interfaces (GUIs) for ESP32 Projects using LVGL (Light Versatile Graphics Library) with the Arduino IDE.

Download Our Free eBooks and Resources

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


[8]ページ先頭

©2009-2025 Movatter.jp