|
17 | 17 | #include "ArduinoHttpServerDebug.h" |
18 | 18 |
|
19 | 19 | #include <Arduino.h> |
| 20 | +#include <Base64.h> |
20 | 21 |
|
21 | 22 | #include <string.h> |
22 | 23 |
|
@@ -64,6 +65,9 @@ class StreamHttpRequest |
64 | 65 | const ErrorString getError() const; |
65 | 66 | Stream& getStream() { return m_stream; }; |
66 | 67 |
|
| 68 | + // Check if authenticated request |
| 69 | + bool authenticate(const char * username, const char * password) const; |
| 70 | + |
67 | 71 | private: |
68 | 72 |
|
69 | 73 | enum class Error: char { |
@@ -100,6 +104,7 @@ class StreamHttpRequest |
100 | 104 | ArduinoHttpServer::HttpVersion m_version; |
101 | 105 | ArduinoHttpServer::HttpField m_contentTypeField; |
102 | 106 | ArduinoHttpServer::HttpField m_contentLengthField; |
| 107 | + ArduinoHttpServer::HttpField m_authorizationField; |
103 | 108 |
|
104 | 109 | Error m_error; |
105 | 110 | ErrorMessageString m_errorDetail; |
@@ -321,6 +326,10 @@ void ArduinoHttpServer::StreamHttpRequest<MAX_BODY_SIZE>::parseField(char lineBu |
321 | 326 | { |
322 | 327 | m_contentLengthField = httpField; |
323 | 328 | } |
| 329 | + else if(httpField.getType() == ArduinoHttpServer::HttpField::Type::AUTHORIZATION) |
| 330 | + { |
| 331 | + m_authorizationField = httpField; |
| 332 | + } |
324 | 333 | else |
325 | 334 | { |
326 | 335 | // Ignore other fields for now. |
@@ -370,6 +379,40 @@ const ArduinoHttpServer::ErrorString ArduinoHttpServer::StreamHttpRequest<MAX_BO |
370 | 379 | return errorString; |
371 | 380 | } |
372 | 381 |
|
| 382 | +template <size_t MAX_BODY_SIZE> |
| 383 | +bool ArduinoHttpServer::StreamHttpRequest<MAX_BODY_SIZE>::authenticate(const char * username, const char * password) const |
| 384 | +{ |
| 385 | + if (m_authorizationField.getType() == HttpField::Type::NOT_SUPPORTED) |
| 386 | + { |
| 387 | + return false; |
| 388 | + } |
| 389 | + |
| 390 | + if (!m_authorizationField.getValueAsString().startsWith("Basic")) |
| 391 | + { |
| 392 | + DEBUG_ARDUINO_HTTP_SERVER_PRINTLN("Unsupported auth header"); |
| 393 | + return false; |
| 394 | + } |
| 395 | + |
| 396 | + String combinedInput; |
| 397 | + if (!combinedInput.reserve(strlen(username) + strlen(password) + 2)) |
| 398 | + { |
| 399 | + DEBUG_ARDUINO_HTTP_SERVER_PRINTLN("Not enough memory"); |
| 400 | + return false; |
| 401 | + } |
| 402 | + combinedInput += username; |
| 403 | + combinedInput += AHS_F(":"); |
| 404 | + combinedInput += password; |
| 405 | + |
| 406 | + int encodedLength = Base64.encodedLength(combinedInput.length()); |
| 407 | + char encodedString[encodedLength]; |
| 408 | + Base64.encode(encodedString, combinedInput.c_str(), combinedInput.length()); |
| 409 | + |
| 410 | + if (strcmp(m_authorizationField.getValueAsString().c_str()+6,encodedString) == 0) |
| 411 | + { |
| 412 | + return true; |
| 413 | + } |
373 | 414 |
|
| 415 | + return false; |
| 416 | +} |
374 | 417 |
|
375 | 418 | #endif // __ArduinoHttpServer__StreamHttpRequest__ |
0 commit comments