|  | 
|  | 1 | +// SPDX-License-Identifier: LGPL-3.0-or-later | 
|  | 2 | +// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov | 
|  | 3 | + | 
|  | 4 | +// | 
|  | 5 | +// Authentication and authorization middlewares | 
|  | 6 | +// | 
|  | 7 | + | 
|  | 8 | +#include <Arduino.h> | 
|  | 9 | +#ifdef ESP32 | 
|  | 10 | +#include <AsyncTCP.h> | 
|  | 11 | +#include <WiFi.h> | 
|  | 12 | +#elif defined(ESP8266) | 
|  | 13 | +#include <ESP8266WiFi.h> | 
|  | 14 | +#include <ESPAsyncTCP.h> | 
|  | 15 | +#elif defined(TARGET_RP2040) | 
|  | 16 | +#include <WebServer.h> | 
|  | 17 | +#include <WiFi.h> | 
|  | 18 | +#endif | 
|  | 19 | + | 
|  | 20 | +#include <ESPAsyncWebServer.h> | 
|  | 21 | + | 
|  | 22 | +static AsyncWebServer server(80); | 
|  | 23 | + | 
|  | 24 | +static AsyncAuthenticationMiddleware basicAuth; | 
|  | 25 | +static AsyncLoggingMiddleware logging; | 
|  | 26 | + | 
|  | 27 | +void setup() { | 
|  | 28 | +  Serial.begin(115200); | 
|  | 29 | + | 
|  | 30 | +#ifndef CONFIG_IDF_TARGET_ESP32H2 | 
|  | 31 | +  WiFi.mode(WIFI_AP); | 
|  | 32 | +  WiFi.softAP("esp-captive"); | 
|  | 33 | +#endif | 
|  | 34 | + | 
|  | 35 | +  // basic authentication | 
|  | 36 | +  basicAuth.setUsername("admin"); | 
|  | 37 | +  basicAuth.setPassword("admin"); | 
|  | 38 | +  basicAuth.setRealm("MyApp"); | 
|  | 39 | +  basicAuth.setAuthFailureMessage("Authentication failed"); | 
|  | 40 | +  basicAuth.setAuthType(AsyncAuthType::AUTH_BASIC); | 
|  | 41 | +  basicAuth.generateHash();  // precompute hash (optional but recommended) | 
|  | 42 | + | 
|  | 43 | +  // logging middleware | 
|  | 44 | +  logging.setEnabled(true); | 
|  | 45 | +  logging.setOutput(Serial); | 
|  | 46 | + | 
|  | 47 | +  // we apply auth middleware to the server globally | 
|  | 48 | +  server.addMiddleware(&basicAuth); | 
|  | 49 | + | 
|  | 50 | +  // protected endpoint: requires basic authentication | 
|  | 51 | +  // curl -v -u admin:admin  http://192.168.4.1/ | 
|  | 52 | +  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { | 
|  | 53 | +    request->send(200, "text/plain", "Hello, world!"); | 
|  | 54 | +  }); | 
|  | 55 | + | 
|  | 56 | +  // we skip all global middleware from the catchall handler | 
|  | 57 | +  server.catchAllHandler().skipServerMiddlewares(); | 
|  | 58 | +  // we apply a specific middleware to the catchall handler only to log requests without a handler defined | 
|  | 59 | +  server.catchAllHandler().addMiddleware(&logging); | 
|  | 60 | + | 
|  | 61 | +  // standard 404 handler: will display the request in the console i na curl-like style | 
|  | 62 | +  // curl -v -H "Foo: Bar"  http://192.168.4.1/foo | 
|  | 63 | +  server.onNotFound([](AsyncWebServerRequest *request) { | 
|  | 64 | +    request->send(404, "text/plain", "Not found"); | 
|  | 65 | +  }); | 
|  | 66 | + | 
|  | 67 | +  server.begin(); | 
|  | 68 | +} | 
|  | 69 | + | 
|  | 70 | +// not needed | 
|  | 71 | +void loop() {} | 
0 commit comments