ESP32 HTTPClient Library – setAuthorization

Home / References / ESP32 Library / HTTPClient

Description

The setAuthorization method in the ESP32 HTTPClient Library is used to configure authentication credentials for HTTP requests. It simplifies the process of adding HTTP Basic Authentication or custom authorization headers by allowing you to specify a username and password or a pre-encoded authorization string. This is particularly useful when accessing protected web resources, enabling your ESP32 projects to securely interact with APIs or servers requiring authentication.


Syntax and Usage

The setAuthorization method can be used in two distinct ways, depending on how you want to provide the authorization details. Below are the available syntaxes:

  • With Username and Password: Pass a username and password as separate arguments. The method internally combines them into a “username:password” string and encodes it in Base64 for Basic Authentication.
  • With Pre-encoded Authorization String: Provide a single pre-encoded string (e.g., a Base64-encoded token or a custom authorization value). This is useful for advanced authentication types like Bearer tokens when paired with ESP32 HTTPClient Library’s setAuthorizationType method.

For more detailed information and examples of the syntax and usage of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Argument(s)

The setAuthorization method accepts arguments depending on the usage. Here’s a detailed breakdown:

  • For setAuthorization(const char *user, const char *password):
    • user: The username for authentication, passed as a null-terminated C-string (const char *).
    • password: The password for authentication, passed as a null-terminated C-string (const char *).
  • For setAuthorization(const char *auth):
    • auth: A pre-encoded authorization string (e.g., Base64-encoded “username:password” or a token), passed as a null-terminated C-string (const char *).

Return Value

The setAuthorization method does not return a value (i.e., its return type is void). It modifies the internal state of the HTTPClient object by setting the authorization header for subsequent HTTP requests.


Example Codes

Below are practical examples demonstrating each usage of the setAuthorization method.

Example 1: Using Username and Password for Basic Authentication

This example shows how to use setAuthorization with a username and password to access a protected endpoint on httpbin.org. The ESP32 connects to Wi-Fi and sends a GET request with Basic Authentication.

/*
 * Author: Avant Maker
 * Date: February 23, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's setAuthorization to
 * access a protected endpoint on httpbin.org with a 
 * username and password. The ESP32 connects to
 * Wi-Fi and sends a GET request with Basic Authentication.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi");
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;
        http.begin("https://httpbin.org/basic-auth/user/passwd");
        http.setAuthorizationType("Basic");
        http.setAuthorization("user", "passwd"); // Sets Basic Auth with username "user" and password "passwd"
        
        int httpCode = http.GET();
        if (httpCode > 0) {
            String payload = http.getString();
            Serial.println("Response Code: " + String(httpCode));
            Serial.println("Response: " + payload);
        } else {
            Serial.println("Error on HTTP request: " + String(httpCode));
        }
        http.end();
    }
    delay(10000); // Wait 10 seconds before the next request
}

Example 2: Creating ES32 Server and ESP32 Client with Bearer Token Authentication

Note: This example requires a basic understanding of HTTP Bearer Token Authentication. If you are unsure what HTTP Bearer Token Authentication means or need more detailed guidance on the following example codes, please stay tuned. We are building a dedicated tutorial for this purpose.

In this example, we utilize two ESP32s—one functioning as a server and the other as a client.

Below are two ESP32 Arduino code examples:

The first code configures an ESP32 as a web server in AP mode, enabling connections from other clients.
The second code sets up an ESP32 as a web client that interacts with the server established by the first code.
When the client connects to the ESP32 server, it must authenticate using a Bearer Token. If the token is valid, the client is granted access to the server.

Here’s how to use the provided ESP32 Server and Client code examples:

Step 1: Configure and Flash the Server ESP32

  • Connect one ESP32 board to your computer via USB.
  • Upload the provided server code below to this ESP32. This board will function as the server.

Step 2: Verify Server Operation

  • After the upload is complete, open your IDE’s Serial Monitor.
  • Select the server ESP32’s serial port.
  • You should observe the following output:
  Configuring access point...
  AP IP address: 192.168.4.1
  HTTP server started
  • This output confirms that the ESP32 HTTP server has started successfully.

Step 3: Configure and Flash the Client ESP32

  • Connect the second ESP32 board to your computer via a different USB port.
  • Upload the provided client code to this ESP32. This board will function as the client.

Step 4: Observe Client-Server Communication

  • Once the client code upload is complete, open the IDE’s Serial Monitor for the client ESP32.
  • Select the client ESP32’s serial port.
  • You should see output similar to this:
    Connecting to AvantMaker-ESP32-AP
    ....
    WiFi connected
    IP address: 192.168.4.2
    Using Authorization: Bearer AvantMaker2025SecretToken
    Sending POST request...
    HTTP Response code: 200
    Server response: Data received: Code-Source=AvantMaker.com
  • This indicates that the client successfully connected, authenticated with the server, and sent data via a POST request.
  • Simultaneously, observe the Serial Monitor of the server ESP32 (from Step 2). Each successful client connection and data transmission will generate the following output:
    Authentication successful
    Received POST data: Code-Source: AvantMaker.com
  • This further verifies that the server successfully authenticated the client and received the data.

ESP32 Web Server Code (Bearer Token Authentication)

The first code example transforms an ESP32 into a web server operating in Access Point (AP) mode. When executed, the ESP32 creates a Wi-Fi network with the SSID “AvantMaker-ESP32-AP” and allows other devices to connect using the password “12345678”.

Once connected, clients can interact with the server by sending HTTP requests. The server listens for incoming connections on port 80 and defines two endpoints: ‘/’ for handling GET requests and ‘/post’ for handling POST requests.

Authentication is enforced using Bearer Token Authentication, implemented in the checkAuth method. If the client provides a valid token via the “Authorization” header, access is granted. Otherwise, the server responds with a 401 Unauthorized error. The handleRoot method serves a simple HTML page upon successful authentication, while the handlePost method processes incoming POST data and sends back a confirmation response.

/*
 * Author: Avant Maker
 * Date: April 1, 2025
 * Version: 1.0
 * Short Description:
 * This code configures an ESP32 to operate as a Wi-Fi Access Point (AP) 
 * and a web server requiring Bearer Token Authentication. 
 *
 * It serves as the server component for an example demonstrating the 
 * ESP32 HTTPClient library's setAuthorization method (used by the client code).
 * For the complete example and more details, please refer to 
 * AvantMaker.com's ESP32 HTTPClient Library - setAuthorization method reference page:
 * https://avantmaker.com/references/esp32-arduino-core-index/esp32-httpclient-library/esp32-httpclient-library-setauthorization/
 *
 * License: MIT 
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

// AP network credentials
const char* ssid = "AvantMaker-ESP32-AP";
const char* password = "12345678";  // Min 8 characters for AP password

// Authentication token - this should be a long, random string in production
const char* authToken = "AvantMaker2025SecretToken";

// Create web server on port 80
WebServer server(80);

void setup() {
  Serial.begin(115200);
  delay(100);
  
  // Configure access point
  Serial.println("Configuring access point...");
  WiFi.softAP(ssid, password);
  
  // Print AP IP address
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  
  // Define endpoints
  server.on("/", HTTP_GET, handleRoot);
  server.on("/post", HTTP_POST, handlePost);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

bool checkAuth() {
  // Debug: Print all headers received
  Serial.println("Received headers:");
  for (int i = 0; i < server.headers(); i++) {
    Serial.print(server.headerName(i));
    Serial.print(": ");
    Serial.println(server.header(i));
  }
  
  // Check for Authorization header
  if (!server.hasHeader("Authorization")) {
    Serial.println("No Authorization header found");
    server.send(401, "text/plain", "Authentication required");
    return false;
  }
  
  String authHeader = server.header("Authorization");
  
  // Check if authorization is correct
  // Format should be "Bearer YOUR_TOKEN"
  if (authHeader.startsWith("Bearer ")) {
    String token = authHeader.substring(7); // Remove "Bearer " prefix
    token.trim();
    
    if (token == authToken) {
      Serial.println("Authentication successful");
      return true;
    }
  }
  
  Serial.println("Invalid token");
  server.send(401, "text/plain", "Invalid authentication token");
  return false;
}

void handleRoot() {
  if (!checkAuth()) {
    return;
  }
  
  String html = "<!DOCTYPE html><html><body>";
  html += "<h1>ESP32 Web Server</h1>";
  html += "<p>Authentication successful!</p>";
  html += "<p>Use POST request to /post endpoint to send data</p>";
  html += "</body></html>";
  
  server.send(200, "text/html", html);
}

void handlePost() {
  if (!checkAuth()) {
    return;
  }
  
  String message = "";
  
  if (server.hasArg("plain")) {
    message = server.arg("plain");
  } else {
    for (int i = 0; i < server.args(); i++) {
      message += server.argName(i) + ": " + server.arg(i) + "\n";
    }
  }
  
  Serial.println("Received POST data:");
  Serial.println(message);
  
  String response = "Data received: \n" + message;
  server.send(200, "text/plain", response);
}

ESP32 Web Client Code (Bearer Token Authentication)

The second code example turns an ESP32 into a web client that communicates with the web server created by the first code. The client connects to the ESP32 server’s Wi-Fi network using the credentials “AvantMaker-ESP32-AP” and “12345678”.

Once connected, it sends periodic POST requests to the server’s ‘/post’ endpoint. The client uses the HTTPClient library to construct and send HTTP requests. Before sending the request, it sets the appropriate headers, including the “Authorization” header with a Bearer token that matches the server’s expected token. The payload for the POST request contains the string “Code-Source=AvantMaker.com”. After sending the request, the client checks the server’s response and logs both the HTTP response code and the server’s reply.This process repeats every 10 seconds, as defined in the loop method.

/*
 * Author: Avant Maker
 * Date: April 3, 2025
 * Version: 1.0
 * Short Description:
 * This code configures an ESP32 to act as a web client using the HTTPClient library.
 * It connects to the companion ESP32 Web Server Access Point (AP) and sends 
 * authenticated POST requests. 
 *
 * It specifically demonstrates how to prepare credentials and use the 
 * HTTPClient::setAuthorization() method to implement Bearer Token Authentication
 * when communicating with a secured server.
 *
 * This client code is part of an example pair (Client/Server). For the complete 
 * example and more details on HTTPClient authentication, please refer to 
 * AvantMaker.com's ESP32 HTTPClient Library - setAuthorization method reference page:
 * https://avantmaker.com/references/esp32-arduino-core-index/esp32-httpclient-library/esp32-httpclient-library-setauthorization/
 *
 * License: MIT 
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */
 
#include <WiFi.h>
#include <HTTPClient.h>

// AP credentials (to connect to the ESP32 server)
const char* ssid = "AvantMaker-ESP32-AP";
const char* password = "12345678";

// Authentication token - must match the server
const char* authToken = "AvantMaker2025SecretToken";

// Server URL
const char* serverUrl = "http://192.168.4.1";  // Default AP IP for ESP32

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi");
    Serial.println("");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;
        http.begin(String(serverUrl) + "/post");
        http.setAuthorizationType("Bearer"); // Set to Bearer for token-based auth
        http.setAuthorization(authToken); // Example token (replace with a real one for actual use)
        
        // Send POST request with payload
        String payload = "Code-Source=AvantMaker.com";
        Serial.println("Sending POST request...");
        int httpCode = http.POST(payload);

        // Check response
        if (httpCode > 0) {
          String response = http.getString();
          Serial.println("HTTP Response code: " + String(httpCode));
          Serial.println("Server response: " + response);
        } else {
          Serial.print("Error on sending POST request: ");
          Serial.println(httpCode);
          Serial.println(http.errorToString(httpCode));
        }
        http.end();
    }   else {
        Serial.println("WiFi Disconnected, trying to reconnect...");
        WiFi.begin(ssid, password);
        delay(5000);
    }
    delay(10000); // Wait 10 seconds before the next request
}

Example 3: Creating ES32 Server and ESP32 Client with HTTP Basic Authentication

In this example, we need two ESP32s—one acting as a server and the other as a client.

Below are two ESP32 Arduino code examples:

  • The first code sets up an ESP32 as a web server in AP mode, allowing other clients to connect.
  • The second code configures an ESP32 as a web client that communicates with the server created by the first code.

When the client connects to the ESP32 server, it must authenticate using a username:password combination. If authentication is successful, the client gains access to the server.

The way of using these example codes is very similar to Example 2 above. If you need any assistance, please refer to the instructions for Example 2.

ESP32 Web Server Code:

This code configures an ESP32 to operate as a Wi-Fi Access Point (AP) and a web server. The code’s key feature is Basic Authentication, implemented in the checkAuth() function. This function verifies if incoming requests contain a valid “Authorization” header. It extracts the Base64 encoded credentials, compares them against the predefined username and password (encoded using base64::encode), and sends a 401 Unauthorized response if authentication fails or is missing.

The handleRoot() function first calls checkAuth(). If authentication succeeds, it responds with a simple HTML page confirming success. Otherwise, the checkAuth() function handles the 401 response.

Similarly, the handlePost() function also requires successful authentication via checkAuth(). If authorized, it extracts the data sent in the POST request (either from plain body or form arguments like server.arg()), prints the data to the Serial Monitor, and sends a confirmation message back to the client.

/*
 * Author: Avant Maker
 * Date: April 1, 2025
 * Version: 1.0
 * Short Description:
 * This code configures an ESP32 to operate as a Wi-Fi Access Point (AP) 
 * and a web server requiring HTTP Basic Authentication. 
 *
 * It serves as the server component for an example demonstrating the 
 * ESP32 HTTPClient library's setAuthorization method (used by the client code).
 * For the complete example and more details, please refer to 
 * AvantMaker.com's ESP32 HTTPClient Library - setAuthorization method reference page:
 * https://avantmaker.com/references/esp32-arduino-core-index/esp32-httpclient-library/esp32-httpclient-library-setauthorization/
 *
 * License: MIT 
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>
#include <base64.h>

// AP network credentials
const char* ssid = "AvantMaker-ESP32-AP";
const char* password = "12345678";  // Min 8 characters for AP password

// Authentication credentials
const char* username = "avantmaker";
const char* userPassword = "secure123";
String encodedCredentials = base64::encode(String(username) + ":" + String(userPassword));

// Create web server on port 80
WebServer server(80);

void setup() {
  Serial.begin(115200);
  delay(100);
  
  // Configure access point
  Serial.println("Configuring access point...");
  WiFi.softAP(ssid, password);
  
  // Print AP IP address
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  
  // Define endpoints
  server.on("/", HTTP_GET, handleRoot);
  server.on("/post", HTTP_POST, handlePost);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

bool checkAuth() {
  if (!server.hasHeader("Authorization")) {
    server.sendHeader("WWW-Authenticate", "Basic realm=\"ESP32 Server\"");
    server.send(401, "text/plain", "Authentication required");
    return false;
  }
  
  String authHeader = server.header("Authorization");
  
  // Check if authorization type is "Basic"
  if (!authHeader.startsWith("Basic ")) {
    server.sendHeader("WWW-Authenticate", "Basic realm=\"ESP32 Server\"");
    server.send(401, "text/plain", "Invalid authentication type");
    return false;
  }
  
  // Extract encoded credentials
  String receivedEncodedCredentials = authHeader.substring(6);
  
  // Trim any whitespace
  receivedEncodedCredentials.trim();
  
  // Check if credentials match
  if (receivedEncodedCredentials.equals(encodedCredentials)) {
    return true;
  } else {
    server.sendHeader("WWW-Authenticate", "Basic realm=\"ESP32 Server\"");
    server.send(401, "text/plain", "Unauthorized");
    return false;
  }
}

void handleRoot() {
  if (!checkAuth()) {
    return;
  }
  
  String html = "<!DOCTYPE html><html><body>";
  html += "<h1>ESP32 Web Server</h1>";
  html += "<p>Authentication successful!</p>";
  html += "<p>Use POST request to /post endpoint to send data</p>";
  html += "</body></html>";
  
  server.send(200, "text/html", html);
}

void handlePost() {
  if (!checkAuth()) {
    return;
  }
  
  String message = "";
  
  if (server.hasArg("plain")) {
    message = server.arg("plain");
  } else {
    for (int i = 0; i < server.args(); i++) {
      message += server.argName(i) + ": " + server.arg(i) + "\n";
    }
  }
  
  Serial.println("Received POST data:");
  Serial.println(message);
  
  String response = "Data received: \n" + message;
  server.send(200, "text/plain", response);
}

ESP32 Web Client Code:

This code demonstrates an ESP32 acting as a web client that connects to the previously described ESP32 web server.

It handles authentication by encoding the client’s username and password into a Base64 string using base64::encode and send a POST request containing a payload string to server.

/*
 * Author: Avant Maker
 * Date: April 1, 2025
 * Version: 1.0
 * Short Description:
 * This code configures an ESP32 to act as a web client using the HTTPClient library.
 * It connects to the companion ESP32 Web Server Access Point (AP) and sends 
 * authenticated POST requests. 
 *
 * It specifically demonstrates how to prepare credentials and use the 
 * HTTPClient::setAuthorization() method to implement HTTP Basic Authentication
 * when communicating with a secured server.
 *
 * This client code is part of an example pair (Client/Server). For the complete 
 * example and more details on HTTPClient authentication, please refer to 
 * AvantMaker.com's ESP32 HTTPClient Library - setAuthorization method reference page:
 * https://avantmaker.com/references/esp32-arduino-core-index/esp32-httpclient-library/esp32-httpclient-library-setauthorization/
 *
 * License: MIT 
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */
 
#include <WiFi.h>
#include <HTTPClient.h>
#include <base64.h>

// AP credentials (to connect to the ESP32 server)
const char* ssid = "AvantMaker-ESP32-AP";
const char* password = "12345678";

// Authentication credentials
const char* username = "avantmaker";
const char* userPassword = "secure123";

// Server URL (IP address will depend on the server's configuration)
const char* serverUrl = "http://192.168.4.1";  // Default AP IP for ESP32

void setup() {
  Serial.begin(115200);
  delay(100);
  
  // Connect to Wi-Fi
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check WiFi connection status
  if (WiFi.status() == WL_CONNECTED) {
    // Initialize HTTPClient
    HTTPClient http;
    
    // Configure server URL with endpoint
    http.begin(String(serverUrl) + "/post");
    
    // Set authorization header with base64 encoded credentials
    String encodedCredentials = base64::encode(String(username) + ":" + String(userPassword));
    http.setAuthorizationType("Basic");
    http.setAuthorization(encodedCredentials.c_str());
    
    // Set content type
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Send POST request with payload
    String payload = "Code-Source=AvantMaker.com";
    int httpResponseCode = http.POST(payload);
    
    // Check response
    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println("HTTP Response code: " + String(httpResponseCode));
      Serial.println("Server response: " + response);
    } else {
      Serial.print("Error on sending POST request: ");
      Serial.println(httpResponseCode);
    }
    
    // Free resources
    http.end();
    
    // Wait before next request
    delay(10000);  // Send request every 10 seconds
  } else {
    Serial.println("WiFi Disconnected, trying to reconnect...");
    WiFi.begin(ssid, password);
    delay(5000);
  }
}
error: Content is protected !!