In the example. ESP32 web server using SPIFFS, is there any way to put basic authentication?
2 Answers
Hi
There 3 ways
Use esp32 header files instead of esp8266
- https://github.com/me-no-dev/ESPAsyncWebServer
- https://randomnerdtutorials.com/esp32-web-server-spiffs-spi-flash-file-system/
- https://github.com/gmag11/FSBrowserN
- tttapa.github.io/ESP8266/Chap14%20-%20WebSocket.html
try this without spiffs
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "ESPAsyncWebServer.h"
bool is_authentified()
{
Serial.println("Enter is_authentified");
if (server.hasHeader("Cookie"))
{
Serial.print("Found cookie: ");
String cookie = server.header("Cookie");
Serial.println(cookie);
if (cookie.indexOf("ESP=1") != -1)
{
Serial.println("Authentification Successful");
return true;
}
}
Serial.println("Authentification Failed");
return false;
}
void handleLogin()
{
if (server.hasArg("USER") && server.hasArg("PASS"))
{
if (server.arg("USER") == "1" && server.arg("PASS") == "1" )
{
server.sendHeader("Location", "/");
server.sendHeader("Cache-Control", "no-cache");
server.sendHeader("Set-Cookie", "ESP=1");
server.send(301);
Serial.println("Log in Successful");
logged_in = "1";
return;
}
//Incorrect login area
msg = "Wrong username/password..!!";
Serial.println("Log in Failed");
}
///
login form webpage
}
void handleRoot()
{
Serial.println("Enter handleRoot");
String header;
if (!is_authentified())
{
server.sendHeader("Location", "/login");
server.sendHeader("Cache-Control", "no-cache");
server.send(301);
return;
}
//////
your web page
}
server.on("/", handleRoot);
server.on("/login", handleLogin);
Hope it helps
Hi Javier.
You can also follow this unit in the ESP32 course and try to adapt to your case: https://rntlab.com/module-4/making-your-esp32-web-server-password-protected/ using base 64 encoding
Regards,
Sara