cotestatnt / esp-fs-webserver

ESP32/ESP8266 webserver, WiFi manager and web editor Arduino library
MIT License
105 stars 27 forks source link

Add option for requiring HTTP basic authentication on all pages. #46

Closed sjmf closed 3 months ago

sjmf commented 3 months ago

Hi @cotestatnt . Firstly, I wanted to say many thanks for authoring and sharing this library. It has been very useful to me in creating easy-to-code REST HTTP IoT Smart Home devices with ESP8266- one of my current interests.

For the purposes of my project, I wanted to require HTTP basic authentication on all registered server routes for security purposes. While you have already usefully implemented FSWebServer::setAuthentication(const char* user, const char* pswd), this currently only restricts access to the /setup and /edit pages.

To resolve this need, I have introduced a new function, FSWebServer::requireAuthentication(bool require). A user of the esp-fs-webserver library calling this function can enable authentication checks for every request, on all routes. I have implemented this by modification of the FSWebServer::handleRequest() function.

The user simply runs myWebServer.requireAuthentication(true) along with the original setAuthentication() call to turn this feature on from their script. It can be turned off again just as easily, by passing false. For example:

// (exclude other code from simpleServer.ino example to keep this short)
FSWebServer myWebServer(FILESYSTEM, 80);
const char* http_user = "admin";
const char* http_password = "change-me";

void setup(){
  // <snip, extra stuff>
  myWebServer.setAuthentication(http_user, http_password);
  myWebServer.requireAuthentication(true);
  myWebServer.begin();
}

It would be amazing if you felt able to include these changes in your library for other users to enjoy. Please review this pull request, and let me know if you require any further changes to introduce this new feature.

cotestatnt commented 3 months ago

Hello @sjmf and thanks for your contribution!

It's not a feature I usually use, but it can be very useful and certainly adds flexibility to the library. I'll approve your pull request right away