2021年12月6日 星期一

ESP32 Web Server HTTP Authentication

ESP32 Web Server HTTP Authentication 

源自於https://randomnerdtutorials.com/esp32-esp8266-web-server-http-authentication/











/*********

  Rui Santos

  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-web-server-http-authentication/

  

  The above copyright notice and this permission notice shall be included in all

  copies or substantial portions of the Software.

*********/


// Import required libraries

//#ifdef ESP32

  #include <WiFi.h>

  #include <AsyncTCP.h>

//#else

//  #include <ESP8266WiFi.h>

//  #include <ESPAsyncTCP.h>

//#endif

#include <ESPAsyncWebServer.h>


// Replace with your network credentials

//const char* ssid = "REPLACE_WITH_YOUR_SSID";

//const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const char* ssid     = "PTS-2F";

const char* password = "PTS6662594";


const char* http_username = "admin";

const char* http_password = "admin";


const char* PARAM_INPUT_1 = "state";


const int output = 2;


// Create AsyncWebServer object on port 80

AsyncWebServer server(80);


const char index_html[] PROGMEM = R"rawliteral(

<!DOCTYPE HTML><html>

<head>

  <title>ESP Web Server</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>

    html {font-family: Arial; display: inline-block; text-align: center;}

    h2 {font-size: 2.6rem;}

    body {max-width: 600px; margin:0px auto; padding-bottom: 10px;}

    .switch {position: relative; display: inline-block; width: 120px; height: 68px} 

    .switch input {display: none}

    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}

    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}

    input:checked+.slider {background-color: #2196F3}

    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}

  </style>

</head>

<body>

  <h2>ESP Web Server</h2>

  <button onclick="logoutButton()">Logout</button>

  <p>Ouput - GPIO 2 - State <span id="state">%STATE%</span></p>

  %BUTTONPLACEHOLDER%

<script>function toggleCheckbox(element) {

  var xhr = new XMLHttpRequest();

  if(element.checked){ 

    xhr.open("GET", "/update?state=1", true); 

    document.getElementById("state").innerHTML = "ON";  

  }

  else { 

    xhr.open("GET", "/update?state=0", true); 

    document.getElementById("state").innerHTML = "OFF";      

  }

  xhr.send();

}

function logoutButton() {

  var xhr = new XMLHttpRequest();

  xhr.open("GET", "/logout", true);

  xhr.send();

  setTimeout(function(){ window.open("/logged-out","_self"); }, 1000);

}

</script>

</body>

</html>

)rawliteral";


const char logout_html[] PROGMEM = R"rawliteral(

<!DOCTYPE HTML><html>

<head>

  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

  <p>Logged out or <a href="/">return to homepage</a>.</p>

  <p><strong>Note:</strong> close all web browser tabs to complete the logout process.</p>

</body>

</html>

)rawliteral";


// Replaces placeholder with button section in your web page

String processor(const String& var){

  //Serial.println(var);

  if(var == "BUTTONPLACEHOLDER"){

    String buttons ="";

    String outputStateValue = outputState();

    buttons+= "<p><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"output\" " + outputStateValue + "><span class=\"slider\"></span></label></p>";

    return buttons;

  }

  if (var == "STATE"){

    if(digitalRead(output)){

      return "ON";

    }

    else {

      return "OFF";

    }

  }

  return String();

}


String outputState(){

  if(digitalRead(output)){

    return "checked";

  }

  else {

    return "";

  }

  return "";

}


void setup(){

  // Serial port for debugging purposes

  Serial.begin(115200);


  pinMode(output, OUTPUT);

  digitalWrite(output, LOW);

  

  // Connect to Wi-Fi

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    Serial.println("Connecting to WiFi..");

  }


  // Print ESP Local IP Address

  Serial.println(WiFi.localIP());


  // Route for root / web page

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){

    if(!request->authenticate(http_username, http_password))

      return request->requestAuthentication();

    request->send_P(200, "text/html", index_html, processor);

  });

    

  server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request){

    request->send(401);

  });


  server.on("/logged-out", HTTP_GET, [](AsyncWebServerRequest *request){

    request->send_P(200, "text/html", logout_html, processor);

  });


  // Send a GET request to <ESP_IP>/update?state=<inputMessage>

  server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {

    if(!request->authenticate(http_username, http_password))

      return request->requestAuthentication();

    String inputMessage;

    String inputParam;

    // GET input1 value on <ESP_IP>/update?state=<inputMessage>

    if (request->hasParam(PARAM_INPUT_1)) {

      inputMessage = request->getParam(PARAM_INPUT_1)->value();

      inputParam = PARAM_INPUT_1;

      digitalWrite(output, inputMessage.toInt());

    }

    else {

      inputMessage = "No message sent";

      inputParam = "none";

    }

    Serial.println(inputMessage);

    request->send(200, "text/plain", "OK");

  });

  

  // Start server

  server.begin();

}

  

void loop() {

  

}

ESP32/ESP8266 Web Server HTTP Authentication (Username and Password Protected)

Learn how to add HTTP authentication with username and password to your ESP32 and ESP8266 NodeMCU web server projects using Arduino IDE. You can only access your web server if you type the correct user and pass. If you logout, you can only access again if you enter the right credentials.

The method we’ll use can be applied to web servers built using the ESPAsyncWebServer library.

ESP32 ESP8266 NodeMCU Web Server HTTP Authentication Username and Password Protected Arduino IDE

The ESP32/ESP8266 boards will be programmed using Arduino IDE. So make sure you have these boards installed:

Security Concerns

This project is meant to be used in your local network to protect from anyone just typing the ESP IP address and accessing the web server (like unauthorized family member or friend).

If your network is properly secured, running an HTTP server with basic authentication is enough for most applications. If someone has managed to hack your network, it doesn’t matter if you use HTTP or HTTPS. The hacker can bypass HTTPS and get your user/pass.

Project Overview

Let’s take a quick look at the features of the project we’ll build.

ESP32 ESP8266 NodeMCU Password Protected Web Server Project Overview
  • In this tutorial you’ll learn how to password protect your web server;
  • When you try to access the web server page on the ESP IP address, a window pops up asking for a username and password;
  • To get access to the web server page, you need to enter the right username and password (defined in the ESP32/ESP8266 sketch);
  • There’s a logout button on the web server. If you click the logout button, you’ll be redirected to a logout page. Then, close all web browser tabs to complete the logout process;
  • You can only access the web server again if you login with the right credentials;
  • If you try to access the web server from a different device (on the local network) you also need to login with the right credentials (even if you have a successful login on another device);
  • The authentication is not encrypted.

Note: this project was tested on Google Chrome and Firefox web browsers and Android devices.

Installing Libraries – Async Web Server

To build the web server you need to install the following libraries:

These libraries aren’t available to install through the Arduino Library Manager, so you need to copy the library files to the Arduino Installation Libraries folder. Alternatively, in your Arduino IDE, you can go to Sketch Include Library > Add .zip Library and select the libraries you’ve just downloaded.

Web Server Code with Authentication

Copy the following code to your Arduino IDE.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-web-server-http-authentication/
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

// Import required libraries
#ifdef ESP32
  #include <WiFi.h>
  #include <AsyncTCP.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const char* http_username = "admin";
const char* http_password = "admin";

const char* PARAM_INPUT_1 = "state";

const int output = 2;

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <title>ESP Web Server</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html {font-family: Arial; display: inline-block; text-align: center;}
    h2 {font-size: 2.6rem;}
    body {max-width: 600px; margin:0px auto; padding-bottom: 10px;}
    .switch {position: relative; display: inline-block; width: 120px; height: 68px} 
    .switch input {display: none}
    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}
    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}
    input:checked+.slider {background-color: #2196F3}
    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
  </style>
</head>
<body>
  <h2>ESP Web Server</h2>
  <button onclick="logoutButton()">Logout</button>
  <p>Ouput - GPIO 2 - State <span id="state">%STATE%</span></p>
  %BUTTONPLACEHOLDER%
<script>function toggleCheckbox(element) {
  var xhr = new XMLHttpRequest();
  if(element.checked){ 
    xhr.open("GET", "/update?state=1", true); 
    document.getElementById("state").innerHTML = "ON";  
  }
  else { 
    xhr.open("GET", "/update?state=0", true); 
    document.getElementById("state").innerHTML = "OFF";      
  }
  xhr.send();
}
function logoutButton() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/logout", true);
  xhr.send();
  setTimeout(function(){ window.open("/logged-out","_self"); }, 1000);
}
</script>
</body>
</html>
)rawliteral";

const char logout_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <p>Logged out or <a href="/">return to homepage</a>.</p>
  <p><strong>Note:</strong> close all web browser tabs to complete the logout process.</p>
</body>
</html>
)rawliteral";

// Replaces placeholder with button section in your web page
String processor(const String& var){
  //Serial.println(var);
  if(var == "BUTTONPLACEHOLDER"){
    String buttons ="";
    String outputStateValue = outputState();
    buttons+= "<p><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"output\" " + outputStateValue + "><span class=\"slider\"></span></label></p>";
    return buttons;
  }
  if (var == "STATE"){
    if(digitalRead(output)){
      return "ON";
    }
    else {
      return "OFF";
    }
  }
  return String();
}

String outputState(){
  if(digitalRead(output)){
    return "checked";
  }
  else {
    return "";
  }
  return "";
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);

  pinMode(output, OUTPUT);
  digitalWrite(output, LOW);
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    if(!request->authenticate(http_username, http_password))
      return request->requestAuthentication();
    request->send_P(200, "text/html", index_html, processor);
  });
    
  server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(401);
  });

  server.on("/logged-out", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", logout_html, processor);
  });

  // Send a GET request to <ESP_IP>/update?state=<inputMessage>
  server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
    if(!request->authenticate(http_username, http_password))
      return request->requestAuthentication();
    String inputMessage;
    String inputParam;
    // GET input1 value on <ESP_IP>/update?state=<inputMessage>
    if (request->hasParam(PARAM_INPUT_1)) {
      inputMessage = request->getParam(PARAM_INPUT_1)->value();
      inputParam = PARAM_INPUT_1;
      digitalWrite(output, inputMessage.toInt());
    }
    else {
      inputMessage = "No message sent";
      inputParam = "none";
    }
    Serial.println(inputMessage);
    request->send(200, "text/plain", "OK");
  });
  
  // Start server
  server.begin();
}
  
void loop() {
  
}

View raw code

You just need to enter your network credentials (SSID and password) and the web server will work straight away. The code is compatible with both the ESP32 and ESP8266 boards.

As an example, we’re building a web server that controls GPIO 2. You can use the HTTP authentication with any web server built with the ESPAsyncWebServer library.

How the Code Works

We’ve already explained in great details how web servers like this work in previous tutorials (DHT Temperature Web Server or Relay Web Server), so we’ll just take a look at the relevant parts to add username and password authentication to the web server.

Network Credentials

As mentioned previously, you need to insert your network credentials in the following lines:

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting Your Username and Password

In the following variables set the username and password for your web server. By default, the username is admin and the password is also admin. We definitely recommend to change them.

const char* http_username = "admin";
const char* http_password = "admin";

Logout Button

In the index_html variable you should add some HTML text to add a logout button. In this example, it’s a simple logout button without styling to make things simpler.

<button onclick="logoutButton()">Logout</button>

When clicked, the button calls the logoutButton() JavaScript function. This function makes an HTTP GET request to your ESP32/ESP8266 on the /logout URL. Then, in the ESP code, you should handle what happens after receiving this request.

function logoutButton() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "logout", true);
  xhr.send();

One second after you click the logout button, you are redirected to the logout page on the /logged-out URL.

  setTimeout(function(){ window.open("/logged-out","_self"); }, 1000);
}

Handle Requests with Authentication

Every time you make a request to the ESP32 or ESP8266 to access the web server, it will check whether you’ve already entered the correct username and password to authenticate.

Basically, to add authentication to your web server, you just need to add the following lines after each request:

if(!request->authenticate(http_username, http_password))
    return request->requestAuthentication();

These lines continuously pop up the authentication window until you insert the right credentials.

You need to do this for all requests. This way, you ensure that you’ll only get responses if you are logged in.

For example, when you try to access the root URL (ESP IP address), you add the previous two lines before sending the page. If you enter the wrong credentials, the browser will keep asking for them.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  if(!request->authenticate(http_username, http_password))
    return request->requestAuthentication();
  request->send_P(200, "text/html", index_html, processor);
});

Here’s another example for when the ESP receives a request on the /state URL.

server.on("/state", HTTP_GET, [] (AsyncWebServerRequest *request) {
  if(!request->authenticate(http_username, http_password))
    return request->requestAuthentication();
  request->send(200, "text/plain", String(digitalRead(output)).c_str());
});

Handle Logout Button

When you click the logout button, the ESP receives a request on the /logout URL. When that happens send the response code 401.

server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send(401);
});

The response code 401 is an unauthorized error HTTP response status code indicating that the request sent by the client could not be authenticated. So, it will have the same effect as a logout – it will ask for the username and password and won’t let you access the web server again until you login.

When you click the web server logout button, after one second, the ESP receives another request on the /logged-out URL. When that happens, send the HTML text to build the logout page (logout_html variable).

server.on("/logged-out", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send_P(200, "text/html", logout_html, processor);
});

Demonstration

Upload the code to your ESP32 or ESP8266 board. Then, open the Serial Monitor and press the on-board RST/EN button to get is IP address.

Open a browser in your local network and type the ESP IP address.

The following page should load asking for the username and password. Enter the username and password and you should get access to the web server. If you haven’t modified the code, the username is admin and the password is admin.

ESP32 ESP8266 NodeMCU Web Server HTTP Authentication type Username and Password

After typing the right username and password, you should get access to the web server.

ESP32 ESP8266 NodeMCU Web Server HTTP Auth Username and Password Protected

You can play with the web server and see that it actually controls the ESP32 or ESP8266 on-board LED.

ESP32 board Built in LED turned on HIGH

In the web server page, there’s a logout button. If you click that button, you’ll be redirected to a logout page as shown below.

If you click the “return to homepage” link, you’ll be redirected to the main web server page.

If you’re using Google Chrome, you’ll need to enter the username and password to access the web server again.

If you’re using Firefox, you need to close all web browser tabs to completely logout. Otherwise, if you go back to the main web server page, you’ll still have access.

So, we advise that you close all web browser tabs after clicking the logout button.

You also need to enter the username and password if you try to get access using a different device on the local network, even though you have access on another device.

ESP32 ESP8266 NodeMCU Web Server HTTP Authentication Username and Password Protected Arduino IDE Demonstration

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...