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.
Basic Authentication
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:
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 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:
Arduino
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…
Hello Luca,
congratulations for the site, I found a little time and has helped me a lot.
Please, I am trying to develop a project with arduino + NIC enc20j60 (the dx.com) and wish I could change the ip address and salver in eeprom, all via the web.
Something like this?
thank you
Hi Sergio,
I’m working on an example about it… stay tuned 😉
Hi Luca,
great tutorial. Thanks a lot especially for the part with arduino code. I will test it soon as can be really helpfull in the projects.
Ciao Luca, innazitutto compilemti per questo splendido sito, volevo porti una domanda ho un problema con una scheda comprata tempo fa su eBay pensado fosse originale invece quando mi è arrivata ho visto che così non era… si tratta di una Arduino Ethernet Shield V1.1 marchiata posteriormente con la sigla FLAMINGO EDA (2009)… ovviamente provandola con la libreria standard per la Ethernet Standard… facendo una ricerca su internet ho scoperto che la libreria si trova a questo link:
http://code.google.com/p/flamingoarduino/source/browse/trunk/hardware/libraries/Ethernet/?r=3
oppure quì (credo sia il produttore):
http://www.flamingoeda.com/2008/09/04/arduino-ethernet-%E7%BD%91%E7%BB%9C%E6%89%A9%E5%B1%95%E6%9D%BF/
quando provo le librerie pero pare che ci sia qualche problema… perchè usando i stessi file d’esempio riportati nella cartella… solo compilando il sorgente genera subito degli errori come se non riuscisse ad utilizzare i file presenti nella libreria… puoi darmi una mano? hai per caso delle librerie aggiornate per questo hardware? perchè presumo che questa libreria sia obsoleta e probabilmente mi da questo problema…
Ciao Cristian,
hai provato ad usare la libreria dei miei tutorial? Dovrebbe essere compatibile… la libreria che linki tu è molto vecchia, probabilmente non è compatibile con l’IDE 1.0.
Hey! Just wanted to give you a thumbs up, and say that your tutorials are some of the best ones out there! Great job, keep it up & many thanks!!
Salve,
sto iniziando a giocare con arduino ed ho appena acquistato la ENC28J60 ( deve ancora arrivare 😀 ). Quello che voglio provare a fare è controllare un relè collegato all’interruttore della caldaia. Naturalmente con un occhio alla sicurezza. Avevo pensato di creare un sito web e collegare arduino UNO ad esso. Ciò che vorrei capire è come poter cifrare i pacchetti tra arduino UNO e il sito web/Cloud. L’unica soluzione che mi viene in mente è quella di assegnare una sorta di ID ad arduino e registrarlo sul mio cloud, poi assegnare l’id ad un specifico utente del cloud e quindi abilitare solo esso ad inviare e ricevere dati da arduino. Anche se qualcuno riesca ad intercettare la chiave necessaria dovrebbe inviare i pacchetti dal cloud ( unico indirizzo abilitato ad impartire comandi ad arduino ), trovate pecche in questa implementazione?
Ciao
direi che è una buona soluzione, purtroppo Arduino non riesce a gestire SSL quindi i pacchetti viaggiano in chiaro ma se abiliti nel tuo sketch un solo IP sorgente (quello del tuo server web) a inviare i comandi dovresti essere abbastanza sicuro!
Ciao Luca,
grazie per il bell’esempio. È applicabile anche per proteggere la pagina index.html di Arduino Yun?
Ciao Paolo
la pagina dello Yun dovrebbe già chiederti una password per accedere e puoi attivare la sicurezza (con la stessa password) anche per tutti i servizi REST dello Yun nelle opzioni: http://arduino.cc/en/Guide/ArduinoYun#toc5
Ciao Luca,
grazie per la pronta risposta. Confermo che, attivando la password per i servizi REST, appare il prompt per username e password, che sono però root e la password di root. Non è una bellissima soluzione, anche se per il momento mi può bastare.
Saluti
Ciao Luca , sono nuovissimo nel mondo arduino. Se ho capito bene la autenticazione richiesta e fatta sulla SDWebServer. E possibile di farla senza uso di SD?
Grazie 1000
ciao! no, l’esempio di questo tutorial non richiede la SD
Ciao Luca, scusa per la mia ignoranza , ho letto che bisogna salvare file ” Dobbiamo quindi specificare la posizione del file .htpasswd,
e li non capisco cosa bisogna fare.
Grazie 1000