ESP32 WebServer Library – authenticate()

Home / References / ESP32 Library / WebServer Library

Description

The authenticate() method is part of the ESP32 WebServer library and is used to implement HTTP Basic Authentication in your web server applications. This method verifies user credentials against predefined username and password combinations, allowing you to protect specific pages or resources on your ESP32 web server from unauthorized access.


Syntax and Usage

The authenticate() method can be used in two different ways:

  • Checking authentication against predefined credentials – Verifies if the client has provided valid authentication credentials that match the predefined username and password.
  • Checking authentication without arguments – Verifies if the client has provided any authentication credentials (useful when credentials are checked elsewhere).
// Method 1: Check authentication against specific credentials
if (!server.authenticate(username, password)) {
    server.requestAuthentication();
    return;
}

// Method 2: Check if client has provided any authentication
if (!server.authenticate()) {
    server.requestAuthentication();
    return;
}

Argument(s)

  • username – A const char pointer containing the username to authenticate against.
  • password – A const char pointer containing the password to authenticate against.

When used without arguments, the method simply checks if the client has provided any authentication credentials.

For practical applications and examples 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.


Return Value

The authenticate() method returns a boolean value:

  • true – Authentication was successful. This means either the client provided credentials that match the username and password (when arguments are provided), or the client has provided any authentication credentials (when no arguments are provided).
  • false – Authentication failed. This means either the client provided credentials that do not match the username and password, or the client hasn’t provided any authentication credentials.

Example Codes

This example demonstrates how to protect the /secure path using HTTP Basic Authentication. Accessing this path will trigger a browser login prompt if the user is not already authenticated.

Explanation:

  1. The code sets up WiFi connection and starts a WebServer.
  2. It defines the required username (auth_user) and password (auth_pass). Remember to change these to something secure in a real application.
  3. A handler handleSecure() is registered for the path /secure.
  4. Inside handleSecure():
    • It first calls server.authenticate(auth_user, auth_pass).
    • If `authenticate` returns false, it means credentials are required or wrong. The code then calls server.requestAuthentication(BASIC_AUTH, "ESP32 Secure Zone") to send a 401 response, prompting the user with the realm “ESP32 Secure Zone”. The return ensures no further code in the handler is executed.
    • If `authenticate` returns true, it means the user provided correct credentials. The code then proceeds to send the actual content of the secure page.
  5. A handler for the root path / is also added for basic navigation.
  6. To test:
    • Upload the sketch, replacing WiFi credentials. Open Serial Monitor for the IP address.
    • Navigate to http://<ESP32_IP>/. You should see the public page.
    • Navigate to http://<ESP32_IP>/secure.
    • Your browser should pop up a login window asking for a username and password for the realm “ESP32 Secure Zone”.
    • Enter incorrect credentials: You should get an error or be prompted again.
    • Enter the correct credentials (“admin” and “secret”): You should now see the message “Authentication Successful! Welcome to the secure area.”.
    • If you refresh the /secure page, your browser might cache the credentials and grant access directly without prompting again (behavior varies by browser).
/*
 * Author: Avant Maker
 * Date: April 11, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * authenticate() method to protect the /secure 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 = "avantmaker";
const char* auth_pass = "esp32admin"; // CHANGE THIS IN A REAL APPLICATION!

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

  // Check if client credentials match
  if (!server.authenticate(auth_user, auth_pass)) {
    // If not authenticated, request authentication
    Serial.println("Authentication failed, requesting credentials.");
    // Send 401 Unauthorized response with WWW-Authenticate header
    return server.requestAuthentication(BASIC_AUTH, "ESP32 Secure Zone");
  }

  // If authentication was successful:
  Serial.println("Authentication successful!");
  server.send(200, "text/plain", "Authentication Successful! Welcome to the secure area.");
}

// Handler for the root page (public)
void handleRoot() {
  server.send(200, "text/html", "<h1>AvantMaker ESP32 Web Server</h1><p>This is the public page.</p><p>Try accessing the <a href=\"/secure\">secure page</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 secure path
  server.on("/secure", HTTP_GET, handleSecure);

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

void loop() {
  server.handleClient();
}
error: Content is protected !!