From 4843a55e59c41236db9ac284d309d0c218e0e7b1 Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Thu, 3 Oct 2024 01:05:19 +0200 Subject: [PATCH] AuthenticationMiddleware bug fixes --- src/ESPAsyncWebServer.h | 26 ++++++++++++++++++++------ src/Middleware.cpp | 7 +++++-- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/ESPAsyncWebServer.h b/src/ESPAsyncWebServer.h index 3c23137..d58e948 100644 --- a/src/ESPAsyncWebServer.h +++ b/src/ESPAsyncWebServer.h @@ -166,11 +166,12 @@ typedef enum { RCT_NOT_USED = -1, // this enum is similar to Arduino WebServer's AsyncAuthType and PsychicHttp typedef enum { - AUTH_NONE = 0, - AUTH_BASIC, - AUTH_DIGEST, - AUTH_BEARER, - AUTH_OTHER, + AUTH_NONE = 0, // always allow + AUTH_BASIC = 1, + AUTH_DIGEST = 2, + AUTH_BEARER = 3, + AUTH_OTHER = 4, + AUTH_DENIED = 255, // always returns 401 } AsyncAuthType; typedef std::function AwsResponseFiller; @@ -570,12 +571,25 @@ class AuthenticationMiddleware : public AsyncMiddleware { void setRealm(const char* realm) { _realm = realm; } void setAuthFailureMessage(const char* message) { _authFailMsg = message; } + + // set the authentication method to use + // default is AUTH_NONE: no authentication required + // AUTH_BASIC: basic authentication + // AUTH_DIGEST: digest authentication + // AUTH_BEARER: bearer token authentication + // AUTH_OTHER: other authentication method + // AUTH_DENIED: always return 401 Unauthorized + // if a method is set but no username or password is set, authentication will be ignored void setAuthType(AsyncAuthType authMethod) { _authMethod = authMethod; } - // precompute and store the hash value based on the username, realm, and authMethod + // precompute and store the hash value based on the username, password, realm. + // can be used for DIGEST and BASIC to avoid recomputing the hash for each request. // returns true if the hash was successfully generated and replaced bool generateHash(); + // returns true if the username and password (or hash) are set + bool hasCredentials() { return _hasCreds; } + bool allowed(AsyncWebServerRequest* request); void run(AsyncWebServerRequest* request, ArMiddlewareNext next); diff --git a/src/Middleware.cpp b/src/Middleware.cpp index 1c36ef6..c7e507b 100644 --- a/src/Middleware.cpp +++ b/src/Middleware.cpp @@ -66,7 +66,7 @@ void AuthenticationMiddleware::setPassword(const char* password) { void AuthenticationMiddleware::setPasswordHash(const char* hash) { _credentials = hash; - _hash = true; + _hash = _credentials.length(); _hasCreds = _username.length() && _credentials.length(); } @@ -99,8 +99,11 @@ bool AuthenticationMiddleware::allowed(AsyncWebServerRequest* request) { if (_authMethod == AsyncAuthType::AUTH_NONE) return true; + if (_authMethod == AsyncAuthType::AUTH_DENIED) + return true; + if (!_hasCreds) - return false; + return true; return request->authenticate(_username.c_str(), _credentials.c_str(), _realm.c_str(), _hash); }