1380  Authentication Methods for IoT

1380.1 Learning Objectives

By the end of this chapter, you should be able to:

  • Implement password-based authentication with secure storage
  • Configure certificate-based mutual TLS (mTLS) authentication
  • Design JWT token-based authentication for IoT APIs
  • Implement multi-factor authentication (2FA) using TOTP
  • Select appropriate authentication methods based on security requirements

What is Authentication? Authentication is the process of verifying identity - proving that you (or a device) are who you claim to be. It answers the question: β€œWho are you?”

Authentication vs Authorization: - Authentication: Proves identity (you ARE who you claim) - Authorization: Determines permissions (what you’re ALLOWED to do)

Key terms: | Term | Definition | |β€”β€”|β€”β€”β€”β€”| | Credentials | Information used to prove identity (passwords, certificates, tokens) | | Single-factor | One type of credential (password only) | | Multi-factor (MFA) | Two or more credential types (password + phone code) | | Certificate | Digital document that cryptographically proves identity | | Token | Time-limited credential issued after authentication |

1380.2 Prerequisites

Before diving into this chapter, you should be familiar with:

1380.3 Password-Based Authentication

Password-based authentication is the simplest form but also the most commonly exploited. Proper implementation requires secure password storage and protection against brute-force attacks.

1380.3.1 Secure Password Storage

Never store passwords in plaintext! Use salted hashing:

// Secure password storage with salt and hash
#include "mbedtls/sha256.h"

struct PasswordHash {
  uint8_t salt[16];
  uint8_t hash[32];
};

PasswordHash hashPassword(String password) {
  PasswordHash result;

  // Generate random salt
  for (int i = 0; i < 16; i++) {
    result.salt[i] = random(256);
  }

  // Combine password + salt
  String combined = password;
  for (int i = 0; i < 16; i++) {
    combined += (char)result.salt[i];
  }

  // Hash with SHA-256
  mbedtls_sha256((uint8_t*)combined.c_str(), combined.length(),
                 result.hash, 0);

  return result;
}

bool verifyPassword(String password, PasswordHash stored) {
  // Recompute hash with stored salt
  String combined = password;
  for (int i = 0; i < 16; i++) {
    combined += (char)stored.salt[i];
  }

  uint8_t computed[32];
  mbedtls_sha256((uint8_t*)combined.c_str(), combined.length(),
                 computed, 0);

  // Constant-time comparison (prevents timing attacks)
  return memcmp(computed, stored.hash, 32) == 0;
}

1380.3.2 Why Salted Hashing Matters

Storage Method Attack Time Vulnerability
Plaintext Instant Anyone with database access has all passwords
Unsalted hash Minutes-hours Rainbow table lookup attacks
Salted hash Days-weeks Must brute-force each password individually
PBKDF2/bcrypt Years Computationally expensive, defeats GPUs

Best Practice: Use PBKDF2, bcrypt, or Argon2 with high iteration counts (100,000+) for production systems.

1380.4 Certificate-Based Authentication (X.509)

Certificate-based authentication uses digital certificates to prove identity cryptographically. This is the gold standard for IoT device authentication.

1380.4.1 Mutual TLS (mTLS) Implementation

// Mutual TLS authentication with certificates
#include <WiFiClientSecure.h>

WiFiClientSecure client;

// Device certificate (unique per device)
const char* device_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIICxjCCAa4CAQEwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UEAwwVSW9UIERldmlj\n" \
"-----END CERTIFICATE-----\n";

// Device private key
const char* device_key = \
"-----BEGIN PRIVATE KEY-----\n" \
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7VJTUt9Us8cKj\n" \
"-----END PRIVATE KEY-----\n";

// CA certificate (verify server)
const char* ca_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \
"-----END CERTIFICATE-----\n";

void setup() {
  // Configure mutual TLS
  client.setCACert(ca_cert);           // Verify server
  client.setCertificate(device_cert);  // Present device cert
  client.setPrivateKey(device_key);    // Device private key

  // Connect with mutual authentication
  if (client.connect("mqtt.server.com", 8883)) {
    Serial.println("Mutually authenticated!");
  }
}

1380.4.2 How mTLS Works

Device                              Server
  |                                    |
  |------ TLS ClientHello ------------>|
  |<----- TLS ServerHello + Server Cert|
  |                                    |
  | (Device verifies server cert       |
  |  against trusted CA)               |
  |                                    |
  |------ Device Certificate --------->|
  |                                    |
  |      (Server verifies device cert  |
  |       against trusted CA)          |
  |                                    |
  |<----- TLS Finished ----------------|
  |                                    |
  | (Both parties authenticated,       |
  |  encrypted channel established)    |
WarningTradeoff: Password vs Certificate Authentication

Option A (Password-Based): - User/device credentials stored as salted hashes - Authentication time: 5-10ms (hash comparison) - Susceptible to credential stuffing if passwords are weak/reused - No PKI infrastructure required - Storage: 50-100 bytes per credential

Option B (Certificate-Based): - Public/private key pairs with CA signatures - Authentication time: 50-200ms (signature verification) - Immune to credential stuffing - Requires PKI infrastructure (CA, CRL/OCSP) - Storage: 1-2KB per device certificate - Enables mutual TLS (mTLS)

Decision Factors: Choose passwords for simple deployments with human users. Choose certificates for device-to-device authentication, high-security environments, or when scaling to thousands of devices where password management becomes impractical.

1380.5 Token-Based Authentication (JWT)

JWT (JSON Web Token) is a compact, self-contained token for authenticating API requests. Unlike session cookies, JWTs are stateless - the server doesn’t need to store session data.

1380.5.1 JWT Structure

header.payload.signature
Part Content Purpose
Header {"alg": "HS256", "typ": "JWT"} Specifies signing algorithm
Payload {"device_id": "sensor-42", "exp": 1735689600} Contains claims (device ID, expiration)
Signature HMACSHA256(header + payload, SECRET_KEY) Prevents tampering

1380.5.2 JWT Authentication Flow

%% fig-alt: "JWT token-based authentication sequence diagram showing stateless authentication flow for IoT devices. Step 1: IoT device sends login request with credentials. Step 2: Auth server verifies credentials. Step 3: Auth server returns JWT valid for 24 hours. Step 4: Device includes JWT in API requests. Step 5: API server validates JWT signature and expiration. Step 6: Success or unauthorized response returned."
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#E67E22', 'secondaryColor': '#16A085', 'tertiaryColor': '#E67E22', 'fontSize': '13px'}}}%%
sequenceDiagram
    participant D as IoT Device
    participant A as Auth Server
    participant B as API Server

    D->>A: 1. Login (username + password)
    A->>A: 2. Verify credentials
    A->>D: 3. Return JWT (valid 24 hours)
    Note over D: Device stores JWT securely

    D->>B: 4. API Request<br/>Header: Authorization: Bearer <JWT>
    B->>B: 5. Verify JWT signature<br/>Check expiration<br/>Extract permissions
    alt JWT Valid
        B->>D: 6. 200 OK + Data
    else JWT Invalid/Expired
        B->>D: 6. 401 Unauthorized
    end

Figure 1380.1: JWT authentication flow showing stateless API authentication

1380.5.3 JWT Security Best Practices

Practice Why It Matters Example
Short expiration Limits damage if token stolen 24 hours max (not months)
Strong secret key Prevents signature forgery 256-bit random key (not β€œsecret123”)
HTTPS only Prevents token interception Never send JWT over HTTP
Don’t store sensitive data Payload is Base64-encoded (not encrypted) Store user ID, not passwords
Validate all claims Prevents replay attacks Check exp, iat, scope

1380.6 Multi-Factor Authentication (2FA)

Multi-factor authentication requires two or more independent credentials:

  • Something you know: Password, PIN
  • Something you have: Phone, hardware token, certificate
  • Something you are: Fingerprint, face recognition

1380.6.1 TOTP Implementation (Time-based One-Time Password)

// TOTP (Time-based One-Time Password) for 2FA
#include <TimeLib.h>

String generateTOTP(const char* secret, uint32_t timestamp) {
  // TOTP = HMAC-SHA1(secret, timestamp / 30)
  uint64_t counter = timestamp / 30;

  uint8_t hmac[20];
  // ... HMAC-SHA1 computation ...

  // Extract 6-digit code
  uint32_t offset = hmac[19] & 0x0F;
  uint32_t code = ((hmac[offset] & 0x7F) << 24) |
                  ((hmac[offset + 1] & 0xFF) << 16) |
                  ((hmac[offset + 2] & 0xFF) << 8) |
                  (hmac[offset + 3] & 0xFF);

  code = code % 1000000;
  return String(code);
}

bool verifyTOTP(const char* secret, String userCode) {
  uint32_t timestamp = now();

  // Check current and +/- 1 time window (90 seconds total)
  for (int i = -1; i <= 1; i++) {
    String validCode = generateTOTP(secret, timestamp + (i * 30));
    if (userCode == validCode) {
      return true;
    }
  }

  return false;
}
WarningTradeoff: Single-Factor vs Multi-Factor Authentication

Option A (Single-Factor - Password Only): - One authentication step - 100-500ms total auth time - 95% of IoT breaches exploit weak/default passwords - User friction: Low - Cost per device: Negligible

Option B (Multi-Factor - Password + TOTP): - Two or more authentication steps - 1-3 seconds total auth time - Blocks 99.9% of automated credential attacks - User friction: Moderate - Cost per device: $0-5 (software) or $10-30 (hardware token)

Decision Factors: Choose single-factor for low-risk IoT with no direct internet exposure. Choose MFA for admin interfaces, cloud dashboards, and any system accessible from the internet.

1380.7 Worked Example: Industrial MFA Implementation

Scenario: A manufacturing plant operates 50 industrial PLCs controlling assembly line robots. Operators currently use shared passwords (β€œplc_admin/factory123”). Implement MFA without disrupting 24/7 operations.

Solution Design:

  1. Select MFA factors for industrial environment:

    • Factor 1 (Something you have): RFID badge (already used for building access)
    • Factor 2 (Something you know): 4-digit PIN (quick entry on touchscreen)
  2. Authentication flow:

    Step 1: Operator taps RFID badge on PLC reader
    Step 2: PLC prompts for 4-digit PIN
    Step 3: PLC validates badge ID + PIN hash against auth server
    Step 4: Auth server checks role permissions for this PLC
    Step 5: Access granted for 8-hour shift duration
  3. Role-based permissions: | Role | Start/Stop | Adjust Speed | Change Recipe | Emergency Stop | |β€”β€”|β€”β€”β€”β€”|————–|β€”β€”β€”β€”β€”|β€”β€”β€”β€”β€”-| | Operator | Yes | Yes | No | Yes | | Lead Operator | Yes | Yes | Yes | Yes | | Maintenance | No | No | No | Yes | | Supervisor | Yes | Yes | Yes | Yes |

Result: - Authentication time: 3-5 seconds (badge tap + PIN entry) - Eliminated shared passwords - Full audit trail: WHO did WHAT on WHICH PLC at WHAT TIME - Zero production disruption during rollout

1380.8 Authentication Method Comparison

Method Security Complexity IoT Suitability Best For
Password Low-Medium Low Good Human users, simple devices
Certificate (mTLS) High High Excellent Device-to-device, fleet management
JWT Token Medium-High Medium Good APIs, cloud services
MFA (TOTP) High Medium Good Admin access, sensitive operations
Hardware Token Very High High Moderate Critical infrastructure

%% fig-alt: "Authentication method selection decision tree for IoT: Start with device capabilities - if device has HSM use certificate-based mTLS, if device has persistent storage use device tokens, if highly constrained use pre-shared keys. For user authentication - if high security use MFA, if convenience prioritized use OAuth."
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
flowchart TD
    START["Select Authentication<br/>Method"] --> TYPE{Device or<br/>User Auth?}

    TYPE -->|Device| DHSM{Has Hardware<br/>Security Module?}
    TYPE -->|User| USEC{Security<br/>Requirement?}

    DHSM -->|Yes| CERT["Certificate-based mTLS<br/>Highest security"]
    DHSM -->|No| DSTOR{Has Persistent<br/>Storage?}

    DSTOR -->|Yes| TOKEN["Device Tokens<br/>with refresh"]
    DSTOR -->|No| PSK["Pre-shared Keys<br/>Lightweight"]

    USEC -->|High| MFA["Multi-Factor Auth<br/>Password + Token/Biometric"]
    USEC -->|Medium| OAUTH["OAuth 2.0<br/>with Mobile App"]
    USEC -->|Basic| PASS["Password + Rate Limit<br/>Isolated networks only"]

    CERT --> RECERT["Recommendation:<br/>X.509 certificates<br/>with PKI infrastructure"]
    TOKEN --> RETOKEN["Recommendation:<br/>JWT with rotation<br/>every 24 hours"]
    PSK --> REPSK["Recommendation:<br/>Unique keys per device<br/>Rotate periodically"]
    MFA --> REMFA["Recommendation:<br/>FIDO2/WebAuthn<br/>or TOTP"]
    OAUTH --> REOAUTH["Recommendation:<br/>Authorization code flow<br/>with PKCE"]
    PASS --> REPASS["Recommendation:<br/>Bcrypt hashing<br/>Account lockout"]

    style START fill:#2C3E50,stroke:#16A085,color:#fff
    style TYPE fill:#E67E22,stroke:#d35400,color:#fff
    style DHSM fill:#E67E22,stroke:#d35400,color:#fff
    style DSTOR fill:#E67E22,stroke:#d35400,color:#fff
    style USEC fill:#E67E22,stroke:#d35400,color:#fff
    style CERT fill:#16A085,stroke:#0e6655,color:#fff
    style TOKEN fill:#16A085,stroke:#0e6655,color:#fff
    style PSK fill:#16A085,stroke:#0e6655,color:#fff
    style MFA fill:#16A085,stroke:#0e6655,color:#fff
    style OAUTH fill:#16A085,stroke:#0e6655,color:#fff
    style PASS fill:#7F8C8D,stroke:#5a6b6d,color:#fff

1380.9 Chapter Summary

Authentication methods verify identity before granting access to IoT systems. Password-based authentication remains common but requires secure storage (salted hashing with PBKDF2/bcrypt) and protection against brute-force attacks. Certificate-based authentication (mTLS) provides the highest security for device authentication, enabling bidirectional identity verification through PKI infrastructure.

Token-based authentication (JWT) offers stateless API access with self-contained claims, while multi-factor authentication adds additional verification factors to protect against credential compromise. The choice of authentication method depends on device capabilities, security requirements, and operational constraints.

1380.10 What’s Next

With authentication methods established, the next chapter examines Access Control where you’ll learn to implement RBAC and ABAC policies that determine what authenticated users and devices are allowed to do.

Continue to Access Control β†’