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");