Layer: L6 Presentation ยท Build flags: PC_ENABLE_JWT
What this example teaches
A client presents Authorization: Bearer <jwt>; the device verifies the token's HMAC-SHA-256 signature against a shared secret and reads claims from it. There are no sessions, no per-client state, and no heap - verification is a hash check. Only HS256 is supported (the deterministic, shared-secret choice for a constrained device).
Verify the signature. pc_jwt_bearer_valid() checks the whole Authorization header against the secret. The full header is in req->authorization - JWTs exceed MAX_VAL_LEN, so the parser captures the authorization header whole when PC_ENABLE_JWT is set:
if (!pc_jwt_bearer_valid(req->authorization, (const uint8_t *)JWT_SECRET, strlen(JWT_SECRET))) {
server.add_response_header(id, "WWW-Authenticate", "Bearer");
server.send(id, 401, "text/plain", "invalid or missing token");
return;
}
Authorize on a claim. Beyond "is it valid," you can gate on claims. Step past the "Bearer " scheme to get the bare token, then read a claim with pc_jwt_claim_str() - here requiring role == admin (else 403):
const char *tok = req->authorization + 7;
while (*tok == ' ') tok++;
char role[16];
if (!pc_jwt_claim_str(tok, strlen(tok), "role", role, sizeof(role)) || strcmp(role, "admin") != 0) {
server.send(id, 403, "text/plain", "forbidden: admin role required");
return;
}
For OAuth2-style space-separated scopes, pc_jwt_scope_allows(scope, "telemetry:write") tests one scope within the scope claim (shown commented in the source).
Minting a token. Sign {"sub":...,"role":"admin","exp":...} with HS256 and the demo secret s3cr3t-key using any JWT library or jwt.io; the header comment includes a ready-made token to try.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--project-option="build_flags=-DPC_ENABLE_JWT=1" \
--lib="." examples/L6-Presentation/JWTAuth/JWTAuth.ino
curl -H "Authorization: Bearer $T" http://<ip>/protected # 200 with a valid admin token
curl http://<ip>/protected # 401
Annotated source
The complete sketch (JWTAuth.ino), reproduced verbatim with added explanatory comments:
#define PC_ENABLE_JWT 1
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
static const char *JWT_SECRET = "s3cr3t-key";
static void protected_handler(uint8_t
id,
HttpReq *req)
{
if (!pc_jwt_bearer_valid(req->authorization, (const uint8_t *)JWT_SECRET, strlen(JWT_SECRET)))
{
server.
send(
id, 401,
"text/plain",
"invalid or missing token");
return;
}
const char *tok = req->authorization + 7;
while (*tok == ' ')
tok++;
char role[16];
if (!pc_jwt_claim_str(tok, strlen(tok), "role", role, sizeof(role)) || strcmp(role, "admin") != 0)
{
server.
send(
id, 403,
"text/plain",
"forbidden: admin role required");
return;
}
server.
send(
id, 200,
"text/plain",
"welcome admin - your token is valid");
}
void setup()
{
Serial.begin(115200);
Serial.print("Connecting to WiFi");
{
delay(250);
Serial.print('.');
}
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
int32_t result = server.
begin(80);
if (result < 0)
Serial.printf("begin() failed (error %d)\n", result);
else
Serial.println("JWT-protected server on :80 (GET /protected with a Bearer token)");
}
void loop()
{
}
Single-port HTTP server with deterministic, zero-allocation execution.
void add_response_header(uint8_t slot_id, const char *name, const char *value)
Queue a custom response header for the next send on this slot.
void send(uint8_t slot_id, int code, const char *content_type, const char *payload)
Send an HTTP response with a body and close the connection.
int32_t begin(const WebServerConfig *cfg=nullptr)
Initialize all connection slots and open all registered listeners.
void on(const char *path, HttpMethod method, Handler callback)
Register a route handler.
void handle()
Drive the server - call every Arduino loop() iteration.
Zero-heap JWT (JSON Web Token) bearer-auth verification, HS256.
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
@ HTTP_GET
Safe, idempotent read.
Fully-parsed HTTP/1.1 request.