ESP32 WebServer Library – requestAuthentication()

Home / References / ESP32 Library / WebServer Library

Description

The requestAuthentication() method is part of the ESP32 WebServer library and is used to trigger the HTTP authentication dialog in a client’s browser. This method is typically called after an authentication check has failed, prompting the user to enter valid credentials. It works in conjunction with authentication methods like authenticate() and authenticateBasicSHA1() to implement secure access control for your ESP32 web server applications.


Syntax and Usage

The requestAuthentication() method can be used in three different ways:

  • Default Authentication Request – Requests authentication using HTTP Basic Authentication with a default realm name.
  • Custom Realm Authentication Request – Requests authentication using HTTP Basic Authentication with a custom realm name.
  • Digest Authentication Request – Requests authentication using HTTP Digest Authentication (more secure than Basic Authentication).
// Method 1: Default Basic Authentication request
server.requestAuthentication();

// Method 2: Basic Authentication with custom realm
server.requestAuthentication(BASIC_AUTH, "Custom Realm", "Authentication failed");

// Method 3: Digest Authentication
server.requestAuthentication(DIGEST_AUTH, "Secure Area", "Authentication failed");

Argument(s)

  • authMode (optional) – Enum value determining the authentication mode. Can be:
    • BASIC_AUTH – Uses HTTP Basic Authentication (default if not specified)
    • DIGEST_AUTH – Uses HTTP Digest Authentication (more secure)
  • realm (optional) – A const char pointer containing the realm name that will be displayed in the authentication dialog. If not specified, a default realm is used.
  • authFailMsg (optional) – A const char pointer containing a custom message that appears when authentication fails. If not specified, a default message is used.

When used without arguments, the method uses HTTP Basic Authentication with default realm and failure message.


Return Value

The requestAuthentication() method does not return a value. It sends the HTTP authentication request headers to the client, which will trigger the browser’s authentication dialog.

Important note: After calling requestAuthentication(), you should typically return from the current handler function to stop further processing, as the client needs to respond with credentials before accessing the protected content.


Example Codes

Example 1

This example demonstrates how requestAuthentication() is used within a handler function to protect a resource using HTTP Basic Authentication. It shows the typical pattern where it’s called only when an authentication check fails.

Explanation:

  1. The code sets up WiFi and a WebServer instance.
  2. It defines credentials (`auth_user`, `auth_pass`).
  3. A handler `handleAdmin()` is registered for the `/admin` path.
  4. Inside `handleAdmin()`:
    • server.authenticate(auth_user, auth_pass) is called first to check credentials sent by the browser.
    • If `authenticate()` returns `false` (meaning no credentials were sent, or they were incorrect), the code immediately executes `return server.requestAuthentication(BASIC_AUTH, “ESP32 Admin Area”);`.
    • This call sends the 401 response with the `WWW-Authenticate: Basic realm=”ESP32 Admin Area”` header, prompting the user to log in. The `return` statement ensures the rest of the handler code (which sends the success message) is skipped.
    • If `authenticate()` returns `true`, the `requestAuthentication()` call is skipped, and the server proceeds to send the “200 OK” response with the protected content.
  5. To test:
    • Upload the sketch (with your WiFi details). Get the IP from Serial Monitor.
    • Navigate to http://<ESP32_IP>/admin.
    • Since you haven’t provided credentials, the `authenticate()` check will fail.
    • The `requestAuthentication()` method will be called, and your browser should display a login prompt showing the realm “ESP32 Admin Area”.
    • Enter the correct username (`admin`) and password (`esp_secret`).
    • The browser will resend the request, this time including the credentials. `authenticate()` will succeed, and you will see the “Admin Area Access Granted!” message.
/*
* Author: Avant Maker
* Date: April 12, 2025
* Version: 1.0
* License: MIT 
* 
* Description: 
* This example demonstrates how to use ESP32 WebServer Library's 
* requestAuthentication() method to protect the /admin path using HTTP
* Basic Authentication.
*
* 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/home/all-about-esp32-arduino-core-library/
*
* 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>

// Replace with your network credentials
const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

WebServer server(80);

// Define username and password for authentication
const char* auth_user = "admin";
const char* auth_pass = "esp_secret"; // Change in a real application

// Handler for the protected admin resource
void handleAdmin() {
  Serial.println("Attempting to access /admin");

  // 1. Check if client credentials match
  if (!server.authenticate(auth_user, auth_pass)) {
    // 2. If authentication fails (no credentials sent or incorrect):
    Serial.println("Authentication failed, requesting credentials.");
    // Send 401 Unauthorized response using requestAuthentication()
    // This includes the WWW-Authenticate header to trigger the browser login prompt.
    // We specify the mode (BASIC_AUTH) and the realm shown to the user.
    return server.requestAuthentication(BASIC_AUTH, "ESP32 Admin Area");
  }

  // 3. If authentication was successful (code reaches here only if authenticate() returned true):
  Serial.println("Authentication successful!");
  server.send(200, "text/plain", "Admin Area Access Granted!");
}

// Handler for the root page (public)
void handleRoot() {
  server.send(200, "text/html", "<h1>ESP32 Web Server</h1><p>Public Page.</p><p>Try accessing the <a href=\"/admin\">Admin Area</a>.</p>");
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Connecting to WiFi...");

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // Register public root handler
  server.on("/", HTTP_GET, handleRoot);

  // Register the handler for the protected admin path
  server.on("/admin", HTTP_GET, handleAdmin);

  server.begin();
  Serial.println("HTTP server started.");
  Serial.print("Protected path is /admin (User: ");
  Serial.print(auth_user);
  Serial.print(", Pass: ");
  Serial.print(auth_pass);
  Serial.println(")");
}

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

Example 2: Basic Authentication with Default Parameters

This example demonstrates how to use requestAuthentication() with default parameters to implement simple HTTP Basic Authentication for a protected page.

/*
* Author: Avant Maker
* Date: April 12, 2025
* Version: 1.0
* License: MIT 
* 
* Description: 
* This example demonstrates how to use ESP32 WebServer Library's 
* requestAuthentication() with a custom realm name and failure
* message to provide a more personalized authentication experience.
*
* 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/home/all-about-esp32-arduino-core-library/
*
* 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>

const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

// Authentication credentials
const char* www_username = "avantmaker";
const char* www_password = "esp32admin";

WebServer server(80);

void setup() {
  Serial.begin(115200);
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  
  // Route for root / web page (public)
  server.on("/", HTTP_GET, []() {
    server.send(200, "text/html", 
      "<!DOCTYPE html><html>"
      "<head><title>ESP32 Authentication Demo</title></head>"
      "<body>"
      "<h1>AvantMaker ESP32 Authentication Demo</h1>"
      "<p>This is a public page</p>"
      "<p><a href='/protected'>Access Protected Page</a></p>"
      "</body></html>");
  });
  
  // Route to handle /protected (requires authentication)
  server.on("/protected", HTTP_GET, []() {
    // Check if the client has valid credentials
    if (!server.authenticate(www_username, www_password)) {
      // If not authenticated, request authentication with default parameters
      server.requestAuthentication();
      return; // Important: stop execution here
    }
    
    // If authenticated, send the protected content
    server.send(200, "text/html", 
      "<!DOCTYPE html><html>"
      "<head><title>Protected Page</title></head>"
      "<body>"
      "<h1>Protected Page</h1>"
      "<p>This page is protected with authentication.</p>"
      "<p>Welcome, authenticated user!</p>"
      "<p><a href='/'>Return to Home</a></p>"
      "</body></html>");
  });
  
  server.begin();
}

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

Example 3: Custom Realm and Failure Message

This example demonstrates how to use requestAuthentication() with a custom realm name and failure message to provide a more personalized authentication experience.

/*
* Author: Avant Maker
* Date: April 12, 2025
* Version: 1.0
* License: MIT 
* 
* Description: 
* This example demonstrates how to use ESP32 WebServer Library's 
* requestAuthentication() with a custom realm name and failure
* message to provide a more personalized authentication experience
*
* 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/home/all-about-esp32-arduino-core-library/
*
* 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>

const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

// Authentication credentials
const char* www_username = "avantmaker";
const char* www_password = "esp32admin";

// Custom authentication parameters
const char* auth_realm = "AvantMaker IoT Control Panel";
const char* auth_fail_msg = "Access Denied: Invalid Credentials";

WebServer server(80);

void setup() {
  Serial.begin(115200);
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  
  // Route for root / web page (public)
  server.on("/", HTTP_GET, []() {
    server.send(200, "text/html", 
      "<!DOCTYPE html><html>"
      "<head><title>Custom Auth Demo</title></head>"
      "<body>"
      "<h1>Custom Authentication Demo</h1>"
      "<p>This is a public page</p>"
      "<p><a href='/admin'>Access Admin Panel</a></p>"
      "</body></html>");
  });
  
  // Route to handle /admin (requires authentication)
  server.on("/admin", HTTP_GET, []() {
    // Check if the client has valid credentials
    if (!server.authenticate(www_username, www_password)) {
      // If not authenticated, request authentication with custom parameters
      server.requestAuthentication(BASIC_AUTH, auth_realm, auth_fail_msg);
      return; // Important: stop execution here
    }
    
    // If authenticated, send the protected content
    server.send(200, "text/html", 
      "<!DOCTYPE html><html>"
      "<head><title>Admin Panel</title></head>"
      "<body>"
      "<h1>IoT Device Admin Panel</h1>"
      "<p>Welcome to the admin control panel.</p>"
      "<p>This area is protected with custom authentication parameters.</p>"
      "<p><a href='/'>Return to Home</a></p>"
      "</body></html>");
  });
  
  server.begin();
}

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

Important Notes:

  • Always call return after requestAuthentication() to stop further processing of the handler function until the client authenticates.
error: Content is protected !!