Using Basic HTTP-Auth with ESP8266

Globment.de - Blog

Using Basic HTTP-Auth with ESP8266
Sometimes it is necessary to secure your microcontroller application with a password. Since cryptography is not supported on most boards HTTP-Auth can be a basic alternative for simple authentication. This example shows the functions to implement HTTP-Auth on a ESP8266 MCU with Arduino IDE. HTTP-Auth is not very secure but is a possible implementation for local networks.

First the setAuthHandler() function is set to the onNotFound implementation.


        server.onNotFound([]() {                             
          setAuthHandler();
        });

      
In the following code the setAuthHandler function is implemented.
      

        void setAuthHandler() {
          String authHeader = server.header("Authorization");
          Serial.println("Server Auth header " + authHeader);
        
          if (authHeader.equals("")) {
            server.sendHeader("WWW-Authenticate", "Basic realm=\"Restricted Area\"");
            server.send(401, "text/plain", "404: Unauthorized");
          }
          String base64FromHeader = authHeader.substring(authHeader.indexOf(' ') + 1);
        
          if (strcmp(localBase64, base64FromHeader) == 0) {
            if (!handleFileRead(server.uri())) {                 
                server.send(404, "text/plain", "404: Not Found"); 
            }
          } else {
            server.sendHeader("WWW-Authenticate", "Basic realm=\"Restricted Area\"");
            server.send(401, "text/plain", "404: Unauthorized");
          }
        }

      
      
A Basic HTTP-Auth header is encoded in base64 and has the following syntax

        Basic user:password  
        
      
So here the substring with encoded username and password of the HTTP-Auth-Header is retrieved from the HTTP-Auth-Header.

        String base64FromHeader = authHeader.substring(authHeader.indexOf(' ') + 1);
     
In this example localBase64 is a variable with encoded username and password. It is possible to use an other function to save password and username in a database.

      if (strcmp(localBase64, base64FromHeader) == 0) {
        ....
    
If username and password don't match a Unauthorized HTTP-Header is send back to the client.

      server.sendHeader("WWW-Authenticate", "Basic realm=\"Restricted Area\"");
      server.send(401, "text/plain", "404: Unauthorized");