Sub topic 7
Moving to HTTPS
This chapter assumes you can already connect a WiFiNINA board to your network, keep credentials in arduino_secrets.h, and send a plain HTTP GET with WiFiClient. It covers what changes when you switch to HTTPS, how certificate checking works on these boards, and the errors you are most likely to meet.
Why plain HTTP is not enough
HTTP sends every byte in clear text. Anyone on the path between your board and the server can read the request, read the response, or change either one. That path includes your Wi-Fi access point, your internet provider, and every router in between.
HTTPS is HTTP carried inside a TLS session. TLS (Transport Layer Security) gives you three things:
- Confidentiality. The traffic is encrypted, so a bystander sees only scrambled bytes.
- Integrity. Tampering with the data in transit is detected.
- Authentication. The server proves its identity with a certificate, so you know you reached the real
example.comand not an impostor.
Many services now refuse plain HTTP entirely, or redirect it to HTTPS. If you request http:// and receive a 301 or 308 status with a Location: https://... header, the server is asking you to switch.
How the TLS handshake works
Before any HTTP is sent, the client and server perform a handshake. The steps are simplified here.
The important step is the certificate check. The server sends a chain: its own certificate, signed by an intermediate authority, which is signed by a root certificate authority (CA). The board does not trust the server directly. It trusts a small set of root CAs whose certificates it already holds. If the chain leads back to one of those roots, and the name in the certificate matches the host you asked for, the handshake continues.
Where the work happens on WiFiNINA boards
On boards such as the MKR WiFi 1010 and Nano 33 IoT, the TLS code does not run on the main microcontroller. It runs on the u-blox NINA Wi-Fi module, which has its own firmware and its own certificate store. Your sketch only asks the module to open a secure socket.
This has two consequences:
- Your sketch changes very little. You swap the client class and the port.
- The set of trusted root certificates lives in the module's firmware and flash, not in your sketch. If a server uses a root that the module does not have, the connection fails no matter how correct your code is.
The code change
The switch from HTTP is small. WiFiSSLClient replaces WiFiClient, and the port becomes 443.
#include <WiFiNINA.h>
#include "arduino_secrets.h"
WiFiSSLClient client;
const char host[] = "example.com";
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
if (client.connect(host, 443)) {
client.println("GET / HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Connection: close");
client.println();
} else {
Serial.println("TLS connection failed");
}
}
void loop() {
while (client.available()) {
Serial.write(client.read());
}
if (!client.connected()) {
client.stop();
while (true) {}
}
}The request text is identical to the HTTP version. The Host header is still required, and it matters for two reasons. The server uses it to choose which site to serve. When you call client.connect(host, 443) with a hostname, the module also sends that name during the handshake (Server Name Indication, or SNI), which lets a server with many sites present the right certificate.
Pass a hostname, not a bare IP address. Certificates are issued for names, so a connection to an IP address usually fails the name check, and many servers need SNI to answer at all.
Root certificates and the certificate store
A root certificate is a public certificate that a CA publishes. The module ships with a bundle of common roots, but the bundle is fixed at the time its firmware was built. Two problems follow:
- New roots. If a site moves to a CA that was created after your firmware was built, the module will not know it.
- Expired roots. Roots have lifetimes. When a root in the bundle expires, sites that depend on it stop validating.
You fix both by updating the module. The Arduino IDE includes a WiFi101 / WiFiNINA Firmware Updater tool (Tools menu). It does two jobs:
- It updates the NINA firmware to a newer version.
- It uploads SSL root certificates for domains you choose to the module's store.
For a specific site, enter the domain, such as api.example.com:443, in the updater's certificate section and upload it. The updater downloads the root certificate that the server's chain ends in and writes it to the module.
If you maintain many boards, this per-board step is the main operational cost of HTTPS on WiFiNINA hardware. Record which firmware version and which domains each board carries.
What the library checks and what it does not
The module validates the certificate chain against its store and checks that the certificate matches the hostname. That covers the standard attack of an impostor server.
Know the limits:
- The clock matters. Certificates have a validity period. The module obtains the time from the network to check it. If the time is wrong, valid certificates can look expired.
- Pinning is not built in. You cannot easily say "accept only this exact certificate". You trust whatever the stored roots vouch for.
- No built-in revocation checks. If a CA revokes a certificate, the module will usually not find out.
- Failures are coarse.
connect()returns0orfalsewithout saying why. You cannot tell an expired certificate from a missing root from a blocked port using that return value alone.
For most hobby and prototype work this is acceptable. For a product that handles sensitive data, plan for it, and see the security chapter later in this tutorial.
Resource costs
TLS is heavier than plain TCP.
| Aspect | HTTP (`WiFiClient`) | HTTPS (`WiFiSSLClient`) |
|---|---|---|
| Port | 80 | 443 |
| Connection setup | TCP handshake only | TCP handshake plus TLS handshake |
| Time to first byte | Short | Often a second or more |
| Memory use | Low | Higher, held in the Wi-Fi module |
| Data hidden from network | No | Yes |
| Server identity checked | No | Yes, against stored roots |
Opening a new TLS session for every reading is the costly part. If you send data often, send less often or keep the connection open with Connection: keep-alive and reuse it, handling the case where the server closes it. A reading every few seconds is realistic. A reading every 100 ms over a fresh TLS connection is not.
Reading the response
The response comes back decrypted, so the code to read it is the same as for HTTP. You see a status line, headers, a blank line, and then the body. Typical lines look like this:
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 1256
Connection: closePrinting the raw response is good for first tests. The next chapter covers separating headers from body and extracting values.
Two details are specific to HTTPS:
- Large pages arrive in several TLS records.
client.available()can be0while more data is still coming, which is why the loop above checksclient.connected()as well asclient.available(). - A server may answer with
Transfer-Encoding: chunked, which puts hexadecimal size lines inside the body. SendingHTTP/1.1requests invites this. SendingHTTP/1.0often avoids chunking, at the cost of compatibility with some servers.
Common errors
| Symptom | Likely cause | What to try |
|---|---|---|
| `connect()` fails immediately | Wi-Fi is not connected, or DNS failed | Check `WiFi.status()` and try `WiFi.hostByName()` |
| `connect()` fails after a delay | Root certificate missing or expired | Update firmware and upload the domain's certificate with the Firmware Updater |
| Works on a PC browser, fails on the board | The site uses a root newer than the module's bundle | Upload the certificate for that domain |
| Fails only some days or hours | Clock or certificate rotation problem | Check the server's certificate expiry and the board's time |
| Connects, but you get a `301` or `400` | Missing `Host` header, or you asked for `http://` paths on the wrong port | Check the request text and the port |
| Works with a hostname, fails with an IP | Name check fails on an IP address | Use the hostname |
| Output stops partway through | Reading loop exits early | Test `client.connected()` too, not just `client.available()` |
A useful debugging order is: Wi-Fi connected, then DNS resolves, then plain TCP to port 443 opens, then TLS completes. You can test the first steps separately:
#include <WiFiNINA.h>
#include "arduino_secrets.h"
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
IPAddress ip;
if (WiFi.hostByName("example.com", ip)) {
Serial.print("DNS OK: ");
Serial.println(ip);
} else {
Serial.println("DNS failed");
return;
}
WiFiSSLClient client;
if (client.connect("example.com", 443)) {
Serial.println("TLS OK");
client.stop();
} else {
Serial.println("TLS failed: check certificates and firmware");
}
}
void loop() {}If DNS works but TLS fails, the cause is almost always the certificate store or the firmware, not your code.
Do not disable verification
Some other platforms offer a way to skip certificate checking, often called "insecure" mode. It makes errors go away, and it also removes the authentication that makes HTTPS worth using. An attacker on the same network could impersonate the server and read or alter your data. If you are tempted, fix the certificate store instead.
Choosing between HTTP and HTTPS
- Use HTTPS for anything that carries credentials, API keys, personal data, or commands that change something.
- Plain HTTP on a trusted local network, for example to a device in your own house, can be acceptable for non-sensitive readings.
- If a public API supports both, use HTTPS. The extra setup is paid once per board, while the protection applies to every request.
Exercise
Your sketch connects to https://api.example.com from a MKR WiFi 1010. connect(host, 443) returns false, but DNS resolution with WiFi.hostByName() succeeds and the same URL loads in your PC browser. What is the most likely cause, and what do you do?
Show answer
The Wi-Fi module most likely lacks the root certificate that the server's chain ends in, or its firmware is out of date. Open the IDE's Firmware Updater tool, update the NINA firmware if a newer version is offered, then add api.example.com:443 in the certificate section and upload it to the module. Retry the sketch afterwards. Changing the sketch code is not the fix, and you should not look for a way to turn off certificate checking.
Exercise
Why must you pass a hostname such as example.com to client.connect() for an HTTPS request, rather than an IP address?
Show answer
Certificates are issued for names, so the module compares the certificate's name with the host you asked for, and an IP address usually fails that check. The hostname is also sent during the handshake as SNI, which lets a server hosting many sites choose the correct certificate.