Today’s tutorial is about a request by Martin: write a sketch to access to a protected area (using username and password) of a website.
The simplest authentication method HTTP protocol supports is named basic authentication.
If you try to access to a secure area, the server responds to your request with code 401, asking the browser to specify a valid username and password. Usually, the browser displays a dialog for inserting the requested values:
Username and password are joined in a string, with a colon between them (utente:password). This string is then base64 coded and sent to the server using an HTTP header:
Authorization: Basic stringa_base64
For example if your username is luca and the password is MyS3cr3t, you can use an online converter to get the correct string for the Authorization header:
You need to configure your webserver to enable basic authentication on a folder. Most web servers support the configuration through .htaccess files, saved in the same folder.
First, prepare a file with users and their passwords; this file is usually named .htpasswd. Use an online tool to encode the data and type the resulting string in your file; then upload it in the folder to be protected:
Now create a new .htaccess file and paste the following configuration:
AuthType Basic AuthName "Secure folder" AuthUserFile /htdocs/demo/secure/.htpasswd Require valid-user
With AuthType you configure the authentication type (“basic”), while with AuthName you can specify a descriptive name for the secure area.
You must specify the .htpasswd location, using its absolute path. You may find it using a simple php script.
At last, you can configure the webserver to authenticate any valid user included in your .htpasswd file (“valid-user”) or specify the name of single authorized users with Require user username.
Upload the .htaccess file to the folder too:
The complete sketch is available in my GitHub’s repository.
First, the authentication string (already base64 encoded) is defined as a constant:
char authorization PROGMEM = "bHVjYTpNeVMzY3Izdb==";
The request (GET) to the webserver contains the Authorization header:
Stash::prepare(PSTR("GET /demo/secure/ HTTP/1.1" "\r\n" "Host: $F" "\r\n" "Authorization: Basic $F" "\r\n" "\r\n"), website, authorization);
When the response is received, Arduino checks if it contains the value 401 (that means a new authentication request, possibly because your credentials were invalid) or 200 (ok):
if(strstr(reply, "HTTP/1.1 401") != 0) Serial.println("Authorization required :("); else if(strstr(reply, "HTTP/1.1 200") != 0) Serial.println("Access granted! :)");
Here are two screenshots about the sketch running…