how to added a authentication for esp 8266/esp32 web server ?

Example: people want to entered the web sever need to key in SSID and password to entered.

you just create a log in web page same way you'd in web designs, when the log ins match with those pre defined in your sketch....

Check out ArduinoOTA

Deva_Rishi:
Check out ArduinoOTA

i am tried

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <ArduinoOTA.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
ESP8266WebServer server(80);
const char* www_username = "admin";
const char* www_password = "esp8266";
void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    ArduinoOTA.begin();
    
    server.on("/", []() {
      if (!server.authenticate(www_username, www_password)) {
        return server.requestAuthentication();
      }
      server.send(200, "text/plain", "Login ok");
    });
    server.begin();
    
    Serial.println("Open http://192.168.4.1");
    Serial.println(WiFi.localIP());
    Serial.println("/ in your browser to see it working");
    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;
    //reset saved settings
    wifiManager.resetSettings();
    
    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //fetches ssid and pass from eeprom and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    wifiManager.autoConnect("AutoConnectAP");
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();

    
    //if you get here you have connected to the WiFi
    Serial.println("HTTP SERVER CONNECTED:)");
}

void loop() {
  ArduinoOTA.handle();
    
}

i added in the user name and password for my esp8266 web sever .but now i cant go in 192.168.4.1 pages

you forgot to also addserver.handleClient();to your loop() {}

Deva_Rishi:
you forgot to also addserver.handleClient();to your loop() {}

</ in your browser to see it working
*WM: settings invalidated
*WM: THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.
*WM:
*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result:
*WM: 0
*WM:
*WM: Configuring access point...
*WM: AutoConnectAP
*WM: AP IP address:
*WM: 192.168.4.1
*WM: HTTP server started>

yes.After i added this shown on my serial monitor but i still cant login 192.168.4.1 web page throw my browser.

The issue is caused by the combination of OTA and wifimanager (which i never use, and this a pretty good reason not to), wifimanager handles the root of the AP (so you can't access and use that anymore, and takes care of any wifi connection to station made, i got this working by changing the order up a bit

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <ArduinoOTA.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
ESP8266WebServer server(80);
const char* www_username = "admin";
const char* www_password = "esp8266";
void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);    

    
    Serial.println("Open http://192.168.4.1");
    Serial.println(WiFi.localIP());
    Serial.println("/ in your browser to see it working");
    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;
    //reset saved settings
    wifiManager.resetSettings();
    
    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //fetches ssid and pass from eeprom and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    wifiManager.autoConnect("AutoConnectAP");
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();

    
    //if you get here you have connected to the WiFi
    Serial.println("HTTP SERVER CONNECTED:)");
    server.on("/", []() {
      if (!server.authenticate(www_username, www_password)) {
        return server.requestAuthentication();
      }
      server.send(200, "text/plain", "Login ok");
    });
    server.begin();
    ArduinoOTA.begin();
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient(); 
}

after which i could access the page with the ESP in station mode using the wifi network i connected to. unfortunately i had to guess what the new IP address would be (but i tried the ones it has shown up in previously) but found it.
the standard sketch for the OTA makes it a little easier to understand (and leaves the access point for common use)

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

const char* ssid = "ESPap";
const char* password = "";

ESP8266WebServer server(80);

const char* www_username = "admin";
const char* www_password = "esp8266";

void setup() {
  Serial.begin(115200);
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  /*WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if(WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Connect Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }*/
  ArduinoOTA.begin();

  server.on("/", [](){
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();
    server.send(200, "text/plain", "Login OK");
  });
  server.begin();

  /*Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in your browser to see it working");*/
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}

Deva_Rishi:
The issue is caused by the combination of OTA and wifimanager (which i never use, and this a pretty good reason not to), wifimanager handles the root of the AP (so you can't access and use that anymore, and takes care of any wifi connection to station made, i got this working by changing the order up a bit

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

#include <ArduinoOTA.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>        //GitHub - tzapu/WiFiManager: ESP8266 WiFi Connection manager with web captive portal
ESP8266WebServer server(80);
const char* www_username = "admin";
const char* www_password = "esp8266";
void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);

Serial.println("Open http://192.168.4.1");
    Serial.println(WiFi.localIP());
    Serial.println("/ in your browser to see it working");
    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;
    //reset saved settings
    wifiManager.resetSettings();
   
    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

//fetches ssid and pass from eeprom and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    wifiManager.autoConnect("AutoConnectAP");
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();

//if you get here you have connected to the WiFi
    Serial.println("HTTP SERVER CONNECTED:)");
    server.on("/", {
      if (!server.authenticate(www_username, www_password)) {
        return server.requestAuthentication();
      }
      server.send(200, "text/plain", "Login ok");
    });
    server.begin();
    ArduinoOTA.begin();
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}


after which i could access the page with the ESP in station mode using the wifi network i connected to. unfortunately i had to guess what the new IP address would be (but i tried the ones it has shown up in previously) but found it.
the standard sketch for the OTA makes it a little easier to understand (and leaves the access point for common use)

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

const char* ssid = "ESPap";
const char* password = "";

ESP8266WebServer server(80);

const char* www_username = "admin";
const char* www_password = "esp8266";

void setup() {
  Serial.begin(115200);
  WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();
  /WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if(WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Connect Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }
/
  ArduinoOTA.begin();

server.on("/", {
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();
    server.send(200, "text/plain", "Login OK");
  });
  server.begin();

/Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in your browser to see it working");
/
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}

sorry.i had tried this coding the serial monitor shown "^Ep⸮4@H⸮L⸮i|H⸮" i was using esp8266 WEMOS D1 R2 mini board

sorry.i had tried this coding the serial monitor shown "^Ep⸮4@H⸮L⸮i|H⸮" i was using esp8266 WEMOS D1 R2 mini board

and you have the BAUD rate of the Serial monitor set correctly ?

Deva_Rishi:
and you have the BAUD rate of the Serial monitor set correctly ?

yeah i tried 9600 and 115200 both the same.

Oh eh, the standard example (2nd sketch) actually doesn't send anything to the Serial port (it is commented out ) Also due to an inaccuracy in the sketch un-commenting stuff does not quite work as you'd hope (it doesn't show the Ip address correctly since it is not actually in full connection status when it is read) though the AP (ESPap) shows up in your network list and you can connect to it and go to the standard IP 192.168.4.1 and you'll be asked for your credential.

this sketch works fully (if you set the proper ssid & password for your network) and prints out plenty in the Serial monitor for you.

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

const char* ssid = "ESPap";
const char* password = "";
const char* network = "yourSSID";
const char* networkpassword = "yourPASS";

ESP8266WebServer server(80);

const char* www_username = "admin";
const char* www_password = "esp8266";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("----------HttpBasicAuth------------");
  WiFi.softAP(ssid, password);
  Serial.println("Access Point started.");
  Serial.print("ssid : ");
  Serial.println(ssid);
  Serial.print("password ");
  Serial.println(password);

  WiFi.begin(network, networkpassword);
  if(WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Connect Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }
  Serial.print("Connected to Network : ");
  Serial.println(network);
  Serial.println("Reconnecting AP");
  WiFi.reconnect();
  uint8_t elapsed=0;
  while (WiFi.status()!=WL_CONNECTED) {
    Serial.print(".");
    delay (500);
    elapsed++;
    if (elapsed>30) {
      Serial.println("Unable to reconnect, Rebooting");
      delay(1000);
      ESP.restart();
    }
  }
  Serial.println();
  
  Serial.println("Starting Authentication server");
  ArduinoOTA.begin();

  
  Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in your browser to see it working");

  server.on("/", [](){
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();
    server.send(200, "text/plain", "Login OK");
  });
  server.begin();  
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}

Deva_Rishi:
Oh eh, the standard example (2nd sketch) actually doesn't send anything to the Serial port (it is commented out ) Also due to an inaccuracy in the sketch un-commenting stuff does not quite work as you'd hope (it doesn't show the Ip address correctly since it is not actually in full connection status when it is read) though the AP (ESPap) shows up in your network list and you can connect to it and go to the standard IP 192.168.4.1 and you'll be asked for your credential.

this sketch works fully (if you set the proper ssid & password for your network) and prints out plenty in the Serial monitor for you.

#include <ESP8266WiFi.h>

#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266WebServer.h>

const char* ssid = "ESPap";
const char* password = "";
const char* network = "yourSSID";
const char* networkpassword = "yourPASS";

ESP8266WebServer server(80);

const char* www_username = "admin";
const char* www_password = "esp8266";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("----------HttpBasicAuth------------");
  WiFi.softAP(ssid, password);
  Serial.println("Access Point started.");
  Serial.print("ssid : ");
  Serial.println(ssid);
  Serial.print("password ");
  Serial.println(password);

WiFi.begin(network, networkpassword);
  if(WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Connect Failed! Rebooting...");
    delay(1000);
    ESP.restart();
  }
  Serial.print("Connected to Network : ");
  Serial.println(network);
  Serial.println("Reconnecting AP");
  WiFi.reconnect();
  uint8_t elapsed=0;
  while (WiFi.status()!=WL_CONNECTED) {
    Serial.print(".");
    delay (500);
    elapsed++;
    if (elapsed>30) {
      Serial.println("Unable to reconnect, Rebooting");
      delay(1000);
      ESP.restart();
    }
  }
  Serial.println();
 
  Serial.println("Starting Authentication server");
  ArduinoOTA.begin();

Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in your browser to see it working");

server.on("/", {
    if(!server.authenticate(www_username, www_password))
      return server.requestAuthentication();
    server.send(200, "text/plain", "Login OK");
  });
  server.begin(); 
}

void loop() {
  ArduinoOTA.handle();
  server.handleClient();
}

thx i will try it

Hi everybody. I have implemented an a solution for authentication and automatic logout from webserver. It is based on cookies, same as Github arduino-esp "SimpleAutenthification.ino" example

SimpleAuthentificationOneTimeSessionName.ino (5.61 KB)

Hi, everybody

I run web server on ESP8266 and using SPIFFS to serv HTML file!

but i need Authentication on some page, How can i do that?

my code in setup is like this:

server.on("/", handleRoot);
server.on("/changewifipass", HTTP_POST, wifichangePass);
  server.on("/connecttowifi", HTTP_POST, connectToWiFi);
  server.on("/deviceconfig", deviceConfig);
  server.on("/resetfactory", resetFactory);
  server.on("/adminconfig", adminConfig);

and in method:

void wifichangePass()
{

  String currentWiFiPassArg = "";
  String wifiPassArg = "";
  String confirmWiFiPassArg = "";
  currentWiFiPassArg = server.arg("currentWiFiPass");
  wifiPassArg = server.arg("wifiPass");
  confirmWiFiPassArg = server.arg("confirmWiFiPass");
  if (currentWiFiPassArg == "" or wifiPassArg == "")
    server.send(400, "application/json", "{\"result\":\"Bad Request! Please send correct Information.\"}");

  if (currentWiFiPassArg == apPass and wifiPassArg == confirmWiFiPassArg)
  {
    apPass = wifiPassArg;
    writeConfig();
  }
  else
  {
    server.send(400, "application/json", "{\"result\":\"Bad Request! Please send correct Information.\"}");
  }

  server.send(200, "application/json", "{\"result\":\"WiFi Password Changed!\"}");
}

How can i do that?

By starting your own topic for starters, rather than highjacking an old topic.