diff --git a/include/app.h b/include/app.h index 4e23885..f56c82a 100644 --- a/include/app.h +++ b/include/app.h @@ -31,7 +31,7 @@ extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT]; void initConfig(); void saveSettingsNow(); const char* getApiToken(); -bool regenerateApiToken(); +bool refreshApiToken(); void requestSaveNetworkSettings(); void requestSaveSettings(); // Call after releasing lifecycle, MQTT queue and Sensors data locks. diff --git a/src/config.cpp b/src/config.cpp index 98ced40..2de3bea 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -106,6 +106,12 @@ static FileData fsSensorsSettings(&LittleFS, "/sensors.conf", 'e', &sensorsSetti // FileData requests can arrive while the save task is running. static std::mutex settingsSaveMutex; +// Kept in NVS rather than in Settings, so the settings file layout does not change. +static constexpr char API_TOKEN_NAMESPACE[] = "portal"; +static constexpr char API_TOKEN_KEY[] = "api_token"; +static constexpr size_t API_TOKEN_LENGTH = 32; +static char apiToken[API_TOKEN_LENGTH + 1] = ""; + void requestSaveNetworkSettings() { std::lock_guard lock(settingsSaveMutex); fsNetworkSettings.update(); @@ -169,13 +175,6 @@ void saveSettingsNow() { } // API token -// Kept in NVS rather than in Settings, so the settings file layout does not change. - -static constexpr char API_TOKEN_NAMESPACE[] = "otgw"; -static constexpr char API_TOKEN_KEY[] = "api_token"; -static constexpr size_t API_TOKEN_LENGTH = 32; -static char apiToken[API_TOKEN_LENGTH + 1] = ""; - static bool isApiTokenValid(const char* token) { if (strlen(token) != API_TOKEN_LENGTH) { return false; @@ -210,7 +209,7 @@ const char* getApiToken() { return apiToken; } -bool regenerateApiToken() { +bool refreshApiToken() { uint8_t bytes[API_TOKEN_LENGTH / 2]; esp_fill_random(bytes, sizeof(bytes)); @@ -232,7 +231,7 @@ static void loadApiToken() { nvs_close(handle); } - if (!isApiTokenValid(apiToken) && !regenerateApiToken()) { + if (!isApiTokenValid(apiToken) && !refreshApiToken()) { apiToken[0] = '\0'; ESP_LOGW(L_SETTINGS, "Failed to create the API token"); } @@ -952,7 +951,7 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) { } } - // Accepted for restoring a backup; the portal shows the token read-only. + // Both the portal and backup restore accept a hexadecimal token. if (src[S_API_TOKEN].is()) { const JsonString value = src[S_API_TOKEN].as(); diff --git a/src/portal.cpp b/src/portal.cpp index 4927510..ec115ef 100644 --- a/src/portal.cpp +++ b/src/portal.cpp @@ -142,42 +142,24 @@ static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); }); -static constexpr char BEARER_PREFIX[] = "Bearer "; - -// Checks "Authorization: Bearer ". -static bool isApiTokenRequest(AsyncWebServerRequest* request) { - if (!request->hasHeader("Authorization")) { - return false; - } - - const String& header = request->getHeader("Authorization")->value(); - const size_t prefixLength = sizeof(BEARER_PREFIX) - 1; - const char* token = getApiToken(); - const size_t tokenLength = strlen(token); - if (!tokenLength || header.length() != prefixLength + tokenLength || !header.startsWith(BEARER_PREFIX)) { - return false; - } - - // Compare without an early exit. - uint8_t diff = 0; - for (size_t i = 0; i < tokenLength; i++) { - diff |= tolower(static_cast(header[prefixLength + i])) ^ token[i]; - } - - return diff == 0; -} - -// Setting a sensor value also accepts the API token, so a device needs no portal password. -static AsyncMiddlewareFunction sensorValueAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { - if (!isAuthenticationRequired(request) || isApiTokenRequest(request)) { +static AsyncMiddlewareFunction apiAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + if (!isAuthenticationRequired(request)) { return next(); } - if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { - return next(); + // Bearer auth + if (request->authType() == AsyncAuthType::AUTH_BEARER) { + if (request->authenticate(getApiToken())) { + return next(); + } + + auto* response = request->beginResponse(401); + response->addHeader(asyncsrv::T_WWW_AUTH, asyncsrv::T_BEARER); + return request->send(response); } - return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); + // Fallback to basic auth for API requests + return authMiddleware.run(request, next); }); static void initWebSerial() { @@ -422,7 +404,7 @@ static void restApi() { // Send response response->setLength(); request->send(setDownloadFilename(response, "backup", "json")); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Request restart @@ -434,7 +416,7 @@ static void restApi() { // Schedule restart restartTask.resume(15000); request->send(202); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Get network settings @@ -446,7 +428,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Set network settings @@ -489,7 +471,7 @@ static void restApi() { } }); networkSettingsHandler.setMaxContentLength(1024); - networkSettingsHandler.addMiddleware(&authMiddleware); + networkSettingsHandler.addMiddleware(&apiAuthMiddleware); // Scan Wi-Fi @@ -534,7 +516,7 @@ static void restApi() { // Release scan results WiFi.scanDelete(); } - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Get settings @@ -590,7 +572,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Set settings @@ -727,7 +709,7 @@ static void restApi() { request->send(response); }); settingsHandler.setMaxContentLength(3072); - settingsHandler.addMiddleware(&authMiddleware); + settingsHandler.addMiddleware(&apiAuthMiddleware); // Get sensors list @@ -756,7 +738,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Get sensor settings @@ -785,7 +767,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Set sensor settings @@ -870,7 +852,7 @@ static void restApi() { request->send(response); }); sensorSettingsHandler.setMaxContentLength(1024); - sensorSettingsHandler.addMiddleware(&authMiddleware); + sensorSettingsHandler.addMiddleware(&apiAuthMiddleware); // Get sensor measurements @@ -899,7 +881,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Set sensor value (JSON) @@ -955,7 +937,7 @@ static void restApi() { request->send(response); }); sensorValueHandler.setMaxContentLength(64); - sensorValueHandler.addMiddleware(&sensorValueAuthMiddleware); + sensorValueHandler.addMiddleware(&apiAuthMiddleware); // Set sensor value (form) @@ -1028,16 +1010,16 @@ static void restApi() { response->setLength(); response->setCode(201); request->send(response); - }).addMiddleware(&sensorValueAuthMiddleware); + }).addMiddleware(&apiAuthMiddleware); - // Regenerate the API token, revoking the old one - webServer->on(AsyncURIMatcher::exact("/api/portal/token/regenerate"), HTTP_POST, [](AsyncWebServerRequest *request) { + // Refresh the API token, revoking the old one + webServer->on(AsyncURIMatcher::exact("/api/portal/token_refresh"), HTTP_POST, [](AsyncWebServerRequest *request) { if (upgrading || restartTask.scheduled() || restartTask.active()) { return request->send(503); } - if (!regenerateApiToken()) { + if (!refreshApiToken()) { return request->send(500); } @@ -1046,7 +1028,7 @@ static void restApi() { response->setLength(); response->setCode(201); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Get vars @@ -1058,7 +1040,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Set vars auto& varsHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { @@ -1092,7 +1074,7 @@ static void restApi() { } }); varsHandler.setMaxContentLength(1536); - varsHandler.addMiddleware(&authMiddleware); + varsHandler.addMiddleware(&apiAuthMiddleware); // Get info webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) { @@ -1163,7 +1145,7 @@ static void restApi() { // Send response response->setLength(); request->send(response); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); // Get coredump webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) { @@ -1213,7 +1195,7 @@ static void restApi() { // Send response request->send(setDownloadFilename(response, "coredump", "bin")); - }).addMiddleware(&authMiddleware); + }).addMiddleware(&apiAuthMiddleware); } // Initialize portal diff --git a/src_data/locales/cn.json b/src_data/locales/cn.json index d2284aa..3ab0dba 100644 --- a/src_data/locales/cn.json +++ b/src_data/locales/cn.json @@ -369,9 +369,8 @@ "mdns": "使用 mDNS", "apiToken": { "title": "API token", - "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", - "regenerate": "Regenerate token", - "regenerateConfirm": "The current token will stop working. Continue?" + "note": "用于免密访问 API。可以手动输入 32 个字符的令牌,也可以通过刷新按钮生成。
令牌通过请求头 Authorization: Bearer <令牌> 发送。", + "refreshConfirm": "当前令牌将失效。要继续吗?" } }, "system": { diff --git a/src_data/locales/en.json b/src_data/locales/en.json index aefbfb6..8f190fa 100644 --- a/src_data/locales/en.json +++ b/src_data/locales/en.json @@ -369,9 +369,8 @@ "mdns": "Use mDNS", "apiToken": { "title": "API token", - "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", - "regenerate": "Regenerate token", - "regenerateConfirm": "The current token will stop working. Continue?" + "note": "For API access without a password. You can enter a 32-character token manually or generate one with Refresh.
The token is sent in the Authorization: Bearer <token> header.", + "refreshConfirm": "The current token will stop working. Continue?" } }, "system": { diff --git a/src_data/locales/it.json b/src_data/locales/it.json index fe6bc33..1578a1c 100644 --- a/src_data/locales/it.json +++ b/src_data/locales/it.json @@ -369,9 +369,8 @@ "mdns": "Usa mDNS", "apiToken": { "title": "API token", - "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", - "regenerate": "Regenerate token", - "regenerateConfirm": "The current token will stop working. Continue?" + "note": "Per accedere all’API senza password. Il token di 32 caratteri può essere inserito manualmente o generato con Ricarica.
Viene inviato nell’intestazione Authorization: Bearer <token>.", + "refreshConfirm": "Il token attuale smetterà di funzionare. Continuare?" } }, "system": { diff --git a/src_data/locales/nl.json b/src_data/locales/nl.json index 16d42f9..e3a7096 100644 --- a/src_data/locales/nl.json +++ b/src_data/locales/nl.json @@ -369,9 +369,8 @@ "mdns": "Gebruik mDNS", "apiToken": { "title": "API token", - "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", - "regenerate": "Regenerate token", - "regenerateConfirm": "The current token will stop working. Continue?" + "note": "Voor toegang tot de API zonder wachtwoord. Je kunt het token van 32 tekens zelf invoeren of genereren met Vernieuwen.
Het token wordt meegestuurd in de header Authorization: Bearer <token>.", + "refreshConfirm": "Het huidige token werkt daarna niet meer. Doorgaan?" } }, "system": { diff --git a/src_data/locales/ru.json b/src_data/locales/ru.json index 7b64da6..c8af384 100644 --- a/src_data/locales/ru.json +++ b/src_data/locales/ru.json @@ -369,9 +369,8 @@ "mdns": "Использовать mDNS", "apiToken": { "title": "API-токен", - "note": "Позволяет устройству передавать значения датчиков без пароля портала: Authorization: Bearer <токен> для POST /api/sensor/value?id=N. Действует только для этого адреса.", - "regenerate": "Сгенерировать новый токен", - "regenerateConfirm": "Текущий токен перестанет работать. Продолжить?" + "note": "Для доступа к API без пароля. Можно задать вручную (32 символа) или сгенерировать кнопкой Обновить.
Передавайте в заголовке Authorization: Bearer <токен>.", + "refreshConfirm": "Текущий токен перестанет работать. Продолжить?" } }, "system": { diff --git a/src_data/pages/settings.html b/src_data/pages/settings.html index 525db7f..840a951 100644 --- a/src_data/pages/settings.html +++ b/src_data/pages/settings.html @@ -43,35 +43,38 @@