Octet

How do network APIs authenticate you, and how do you handle tokens in a script?

Show the answer

Say this first

Three patterns cover most of it. Basic auth sends a base64 user and password on every call, so it is only acceptable over TLS. Token APIs (Catalyst Center, APIC) take a login call once and return a short-lived token you send in a header. API keys and OAuth 2.0 bearer tokens (Meraki, cloud platforms) go in the Authorization header. In scripts I keep credentials out of the code, verify TLS, and handle a 401 by getting a fresh token and retrying once.

Go deeper

Examples

PlatformHow you log inHow you send it after
IOS-XE RESTCONFBasic auth on every requestAuthorization: Basic ...
Catalyst CenterPOST /dna/system/api/v1/auth/token with basic auth, returns {"Token": "..."}X-Auth-Token header
ACI APICPOST /api/aaaLogin.json with user and password in JSONAPIC-cookie cookie; refresh with /api/aaaRefresh.json
Meraki DashboardAPI key created in the dashboardAuthorization: Bearer <key>

A clean Python pattern

Python
import os
import requests

BASE = "https://catc.example.com"
CA = "/etc/ssl/certs/corp-ca.pem"

resp = requests.post(
    f"{BASE}/dna/system/api/v1/auth/token",
    auth=(os.environ["CATC_USER"], os.environ["CATC_PASS"]),
    verify=CA,
    timeout=10,
)
resp.raise_for_status()
token = resp.json()["Token"]

devices = requests.get(
    f"{BASE}/dna/intent/api/v1/network-device",
    headers={"X-Auth-Token": token, "Accept": "application/json"},
    verify=CA,
    timeout=30,
)
devices.raise_for_status()
for dev in devices.json()["response"]:
    print(dev["hostname"], dev["managementIpAddress"])

Habits that matter

  • Credentials come from environment variables, Ansible Vault or a secrets manager, never from the repo.
  • verify=False is a lab shortcut. In production point verify at the company CA bundle.
  • Tokens expire. A long job must refresh or re-authenticate on 401 instead of failing halfway.
  • Use a dedicated service account with only the rights the job needs, so the AAA logs show what the automation did.

Traps

  • Hard-coding a password in a script and committing it to Git. History keeps it even after you delete it.
  • Disabling certificate checks in production code.
How did you do?