5  Authentication and Access Control

Building Secure IoT Access Systems

Learning Objectives

After completing this module, you will be able to:

  • Distinguish between authentication (identity verification) and authorization (permission enforcement) in IoT systems
  • Implement role-based access control with multi-level privilege hierarchies on embedded devices
  • Design token lifecycle management including creation, validation, renewal, and revocation
  • Apply capability-based access control with bit-flag permissions for fine-grained resource protection
In 60 Seconds

IoT authentication verifies device and user identity (who you are) while access control enforces what they can do (what you are allowed). Together they prevent unauthorized device access, protect sensitive sensor data, and enable fine-grained permission management across heterogeneous IoT device fleets. Both must be designed in from the start — retrofitting authentication and access control to existing IoT systems is costly and error-prone.

Access control determines what each user or device is allowed to do in an IoT system. Think of a hospital where doctors, nurses, and visitors each have different access levels – doctors can prescribe medication, nurses can administer it, and visitors can only visit patients. Similarly, IoT access control ensures each device and user can only perform actions appropriate to their role.

“Stop right there!” Sammy the Sensor called out, playing security guard. “Before you can talk to any of us IoT devices, you need to answer two questions: WHO are you, and WHAT are you allowed to do?”

Max the Microcontroller explained the difference. “Authentication is like checking someone’s ID badge at the door. It answers ‘Who are you?’ Authorization comes next – it checks which rooms that person can enter. You might have a valid badge but still be restricted from certain areas.”

“This module takes you from fundamentals all the way to enterprise-grade security,” Lila the LED said. “First you learn the concepts: what authentication means, what authorization means, and the AAA framework. Then you build real systems with RFID cards, role hierarchies, and token management on actual ESP32 hardware!”

“By the end, you will be able to implement token-based authentication, role-based access control with admin, user, and guest levels, capability-based fine-grained permissions, and complete audit logging,” Bella the Battery summarized. “These are the same patterns used in OAuth 2.0, AWS IAM, and Kubernetes RBAC – just scaled down to run on a microcontroller. Start with the fundamentals chapter and work your way up!”

5.1 Overview

This comprehensive module covers authentication and access control for IoT systems, from fundamental concepts to enterprise-grade implementations. Learn to build secure access control systems that verify identity (authentication), check permissions (authorization), and log all activity (accounting).

Module Structure

This topic has been organized into focused chapters for easier learning:

  1. Fundamentals - Core concepts of authentication vs authorization, the AAA framework
  2. Basic Lab Setup - Hardware components, circuit design, and code structure
  3. Basic Lab Implementation - Complete working RBAC code with testing and lockout policies
  4. Advanced Concepts - Capability-based access control, tokens, sessions, and ABAC
  5. Advanced Lab Implementation - Enterprise-grade security patterns with privilege escalation prevention

5.2 Learning Path

5.2.1 Beginner Path

Start with the fundamentals to understand the core concepts:

Chapter Focus Time
Authentication Fundamentals Auth vs Authz, AAA framework 30 min
Basic Lab Setup Components, circuit, code structure 45 min
Basic Lab Implementation Full implementation, testing 60 min

5.2.2 Advanced Path

After completing the basics, explore enterprise-grade patterns:

Chapter Focus Time
Advanced Concepts Capabilities, tokens, sessions 45 min
Advanced Lab Implementation Full enterprise implementation 90 min

5.3 Key Concepts Covered

5.3.1 Authentication vs Authorization

Security concept diagram illustrating authentication (verifying who a user or device is via credentials, tokens, or certificates) versus authorization (determining what actions they are permitted to perform via RBAC, ABAC, or capability-based policies) within IoT access control systems

Authentication and access control security concepts showing the distinction between identity verification and permission enforcement in IoT systems

5.3.2 The AAA Framework

Component Question Purpose
Authentication Who are you? Verify identity
Authorization What can you do? Check permissions
Accounting What did you do? Audit trail

OAuth 2.0 Device Flow Token Lifecycle Economics:

For a streaming service with 10 million smart TV devices implementing OAuth 2.0 device flow (RFC 8628), the token lifecycle has measurable costs and security trade-offs.

Access Token Lifetime (1 hour): \[ \text{Refresh events/day} = \frac{24 \text{ hours}}{1 \text{ hour/token}} = 24 \text{ refreshes/device/day} \]

\[ \text{Total API calls/day} = 10^7 \text{ devices} \times 24 = 2.4 \times 10^8 \text{ token refresh requests} \]

At $0.10 per 1,000 API calls: \(\text{Daily cost} = \frac{2.4 \times 10^8}{1000} \times 0.10 = \$24,000/\text{day}\)

Refresh Token Lifetime (90 days): \[ \text{Re-authentication rate} = \frac{10^7 \text{ devices}}{90 \text{ days}} = 111,111 \text{ device code flows/day} \]

Each device code flow involves 12 polling attempts (average) before user completes activation.

\[ \text{Polling overhead} = 111,111 \times 12 = 1.33 \times 10^6 \text{ failed polls/day} \]

Security Trade-off Analysis:

Shorter access token (15 minutes instead of 1 hour):

  • Reduces compromise window: \(1 \text{ hour} \to 15 \text{ minutes} = 75\%\) reduction in exposure time
  • Increases costs: \(24 \text{ daily refreshes} \to 96 = 4\times\) increase = $96,000/day

Longer refresh token (180 days instead of 90):

  • Reduces re-auth friction: \(111,111 \to 55,556 = 50\%\) fewer device activations
  • Increases compromise risk: Stolen refresh token valid for 180 days vs 90 days

Production Recommendation: 1-hour access tokens + 90-day refresh tokens balances security ($24k/day) vs user friction (111k re-auths/day).

5.3.3 Hands-On Labs

Basic Access Control Lab – Build a complete IoT access control system with an ESP32 microcontroller, LED indicators for access states, buzzer for audio feedback, and button-based RFID simulation. Security features demonstrated include token-based authentication, role-based access control, brute force protection via lockout, and comprehensive audit logging.

Advanced Access Control Lab – Extend to enterprise-grade patterns including capability bit flags (12 different permissions), time-limited session tokens, token refresh with rate limiting, privilege elevation with MFA simulation, and escalation attempt detection.


5.4 Quick Start

Choose based on your experience level:

New to Security?

Start with Authentication Fundamentals to understand core concepts before building.

Ready to Build?

Jump to Basic Lab Setup if you understand authentication vs authorization.

Want Advanced Topics?

Go directly to Advanced Concepts if you’ve completed basic RBAC systems.


5.5 Summary

This module teaches you to build secure IoT access control systems that:

  1. Verify identity through multiple authentication methods
  2. Check permissions using role-based and capability-based access control
  3. Prevent attacks through lockout policies and escalation detection
  4. Maintain audit trails for security forensics and compliance

The hands-on labs provide practical experience with real security patterns used in enterprise systems, from basic RFID-style authentication to advanced token lifecycle management.

Learning Progression: Theory (fundamentals) –> Practice (basic lab) –> Extension (advanced concepts) –> Enterprise (advanced lab). This module demonstrates the evolution from basic RBAC (roles = static permission sets) to capability-based access (fine-grained, composable permissions) to ABAC (context-aware decisions), mirroring how production systems mature.

5.6 Knowledge Check

A streaming service implements OAuth 2.0 Device Authorization Grant (RFC 8628) to authenticate smart TVs that have no keyboard for entering passwords. This is the same flow used by Roku, Apple TV, and Google Chromecast.

Step-by-Step Flow:

  1. User launches app on TV
    • TV displays: “Visit https://stream.example.com/activate”
    • TV displays code: XJKL-MNOP
    • TV polls token endpoint every 5 seconds
  2. User opens browser on phone/laptop
    • Visits activation URL
    • Enters code XJKL-MNOP
    • Authenticates with username/password (or Google/Facebook login)
  3. Server validates code
    • Checks: Is code XJKL-MNOP valid and not expired?
    • Links code to user account
  4. TV receives tokens
    • Next poll request receives:
      • Access token (1-hour lifetime)
      • Refresh token (90-day lifetime)
    • TV stores tokens in secure storage

Code Sample (Simplified):

# Step 1: TV requests device code
response = requests.post('https://auth.example.com/device/code', data={
    'client_id': 'smarttv_client',
    'scope': 'stream.read stream.write'
})
device_code = response.json()['device_code']
user_code = response.json()['user_code']  # e.g., "XJKL-MNOP"
verification_uri = response.json()['verification_uri']
interval = response.json()['interval']  # Polling interval (5 seconds)

print(f"Visit {verification_uri} and enter code {user_code}")

# Step 2: TV polls for token
while True:
    time.sleep(interval)
    token_response = requests.post('https://auth.example.com/token', data={
        'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
        'device_code': device_code,
        'client_id': 'smarttv_client'
    })

    if token_response.status_code == 200:
        access_token = token_response.json()['access_token']
        refresh_token = token_response.json()['refresh_token']
        print("Authentication successful!")
        break
    elif token_response.json()['error'] == 'authorization_pending':
        continue  # User hasn't entered code yet
    else:
        print(f"Error: {token_response.json()['error']}")
        break

Production Metrics (Real streaming service data):

  • 92% of users complete activation within 60 seconds
  • 4.2% enter wrong code (user error)
  • 1.1% codes expire (15-minute timeout)
  • Average polling attempts before success: 12 (60 seconds / 5-second interval)
Device Class Constraints Recommended Auth Rationale
Severely constrained MCU (e.g., ATmega328, <32KB RAM) No TLS, limited crypto Pre-shared keys (PSK) + HMAC Minimal overhead, symmetric crypto only
Constrained MCU (ESP32, ~520KB SRAM) TLS possible, no keyboard X.509 client certificates Strong identity, hardware key storage (ATECC608)
Linux gateway/SBC (Raspberry Pi) Full TLS, file system Mutual TLS + OAuth refresh tokens Leverage OS crypto libraries
Consumer device (Smart TV, thermostat) Display-only, no keyboard OAuth 2.0 Device Flow User-friendly, no credential storage on device
Industrial PLC/SCADA Long-lived, critical Mutual TLS + certificate pinning Strongest binding, prevents MITM

Quick Selection Rule:

  1. Human interaction required? –> OAuth 2.0
  2. Device has crypto coprocessor? –> X.509 certificates
  3. Severely resource-constrained? –> PSK
  4. Default for IoT devices –> X.509 with hardware key storage
Common Mistake: Storing Long-Lived Tokens Without Rotation

What practitioners do wrong: They provision IoT devices with API tokens or client secrets during manufacturing and never rotate them, assuming device credentials are “set and forget.”

Why it fails:

  1. Token leakage over time: Firmware updates, diagnostics, and debug logs can leak tokens
  2. Insider threats: Employees who provisioned devices retain access indefinitely
  3. Compliance violations: PCI DSS 4.0 (Requirement 8.3.9) and other standards mandate periodic credential rotation
  4. Breach containment: If one token leaks, you must revoke all tokens (fleet-wide outage)

Correct approach (automated rotation):

For OAuth 2.0 systems:

# Device stores refresh token, not access token
def get_valid_access_token():
    if access_token_expired():
        # Automatic rotation via refresh token
        new_tokens = request_token_refresh(refresh_token)
        save_tokens(new_tokens['access_token'], new_tokens['refresh_token'])
        return new_tokens['access_token']
    return current_access_token

For X.509 certificates:

  • Use short certificate lifetimes (1-2 years, not 10 years)
  • Implement EST (Enrollment over Secure Transport, RFC 7030) for auto-renewal
  • Devices request new certificate 30 days before expiration

For PSK systems:

  • Use key derivation functions (HKDF) to generate per-session keys from master key
  • Rotate master key annually via firmware update + secure boot

Real-world consequence: In 2018, a building automation vendor provisioned 80,000 HVAC controllers with a shared API key valid for 10 years. When the key leaked via a GitHub commit in 2020, they had no rotation mechanism. Options: (1) Brick all devices and ship replacements ($12M), or (2) Deploy emergency firmware with new key ($3M + 6 months). They chose option 2. Post-incident: 90-day OAuth tokens with auto-refresh.

5.7 See Also

Within This Module:

  • All five chapters form a complete learning path from basics to advanced
  • Hands-on labs use ESP32 hardware (available via Wokwi simulator)
  • 17 interactive knowledge checks reinforce learning

Related Security Modules:

Production Examples:

  • OAuth 2.0 (RFC 6749) - Authorization framework for web and IoT
  • JSON Web Tokens (JWT) - Compact token format
  • AWS IAM - Cloud access policies with fine-grained permissions
  • Kubernetes RBAC - Container access control with role bindings

Common Pitfalls

A single shared certificate eliminates the ability to revoke individual compromised devices — revoking the shared certificate takes down the entire fleet. Each device must have a unique certificate enabling per-device revocation while the rest of the fleet continues operating.

IoT devices deployed for 10 years often have certificates valid for only 1–3 years. Without planning OTA certificate renewal, devices will become unable to authenticate when their certificates expire. Implement renewal at least 90 days before expiry with a fallback recovery mechanism.

Accepting device registrations without any pre-shared secret or certificate allows attackers to register fake devices. Use pre-provisioned certificates or a registration secret issued at manufacture to authenticate the registration request.

Assuming that devices on the internal network are trustworthy and don’t need authentication enables lateral movement attacks. An attacker who compromises one device can then reach all others without authentication. Implement mutual authentication for all device-to-device and device-to-cloud communications.

5.8 What’s Next

After mastering authentication and access control, continue with:

If you want to… Read this
Learn the cryptographic foundations of authentication Encryption Principles and Crypto Basics
Apply zero trust to IoT network design Zero Trust Security
Design privacy-preserving IoT systems Privacy by Design
Explore access control for IoT devices IoT Security Access Control
Study authentication methods in practice Authentication Methods for IoT