Today’s tutorial is about a request by Martin: write a sketch to access to a protected area (usingusername and password) of a website.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 HTTPheader:<strong>Authorization: Basic</strong> 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:Server configuration
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 BasicAuthName "Secure folder"AuthUserFile /htdocs/demo/secure/.htpasswdRequire 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:Arduino
The complete sketch is available in my GitHub’s repository.
First, the authentication string (already base64 encoded) is defined as a constant:[color=white !important]
char authorization PROGMEM = "bHVjYTpNeVMzY3Izdb==";
The request (GET) to the webserver contains the Authorization header:[color=white !important]
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):[color=white !important]
if(strstr(reply, "HTTP/1.1 401") != 0)
else if(strstr(reply, "HTTP/1.1 200") != 0)
Here are two screenshots about the sketch running…
For more details,please refer to original post