Skip to content

Authenticating to network APIs with OAuth 2.0

Many cloud-managed network platforms — Webex, and a growing number of SaaS controllers — authenticate with OAuth 2.0 rather than a static API key or a custom token-exchange endpoint. This article explains the two grant types that matter for automation, the shape of the token response, and the proactive refresh and secure-storage habits that keep a long-running job authenticated without a human in the loop.

It is a companion to Consuming REST APIs at scale, which covered the simpler Catalyst Center pattern — POST credentials, get an opaque token back, resend it as X-Auth-Token. OAuth 2.0 is a different model, and worth understanding on its own terms.

Why OAuth 2.0 instead of a static key

A static API key is one long-lived secret sent on every call. If it leaks, it is valid until someone notices and rotates it by hand. OAuth 2.0 replaces that with short-lived access tokens: your automation presents durable credentials once, receives an access token that expires in minutes or hours, and uses that token as a Bearer credential until it expires. A leaked access token is useful only until it times out, and the durable credentials (a client secret, or a refresh token) are sent far less often and can be scoped and revoked independently.

The access token is still a secret — anyone holding it can act as you until it expires — so it is sent over TLS, kept out of logs and URLs, and never committed to Git.

The two grants that matter for automation

OAuth 2.0 defines several grant types (ways to obtain a token). For network automation, two cover almost everything:

Grant Who acts Refresh token? Typical use
Client credentials the application itself (machine-to-machine) No — just request a new one A backend job calling an API as a service identity
Authorization code + refresh a user who delegated access to the app Yes Webex integrations acting on a user's behalf

The client credentials grant (RFC 6749 §4.4) is the one that fits a headless automation runner: there is no user and no browser. The app authenticates with its own client ID and secret and receives an access token directly. The spec notes this grant is for confidential clients and does not issue a refresh token — when the access token expires, you simply run the grant again.

The authorization code grant is what a user-facing integration uses: a person logs in and consents, and the app receives both an access token and a long-lived refresh token it can exchange for new access tokens without asking the user again. Webex integrations work this way — the access token and refresh token have separate, much longer lifetimes (Webex: Integrations & Authorization). For a fully unattended service identity, Webex offers Service Apps, authorized once by an org admin, which then refresh the same way.

The token response

Whatever the grant, a successful request to the token endpoint returns the same JSON shape (RFC 6749 §5.1):

{
  "access_token": "eyJhbGciOi...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
  "scope": "config:read config:write"
}
  • access_token — the credential you send as Authorization: Bearer <token>.
  • token_type — almost always Bearer.
  • expires_in — the access token's lifetime in seconds. This is the number you schedule refreshes against; do not hardcode an assumed lifetime.
  • refresh_token — present only for grants that issue one (not client credentials).
  • scope — the permissions actually granted, which may be narrower than you asked for.

Client credentials in Python

This client fetches a token on first use, sends it as a Bearer header, refreshes proactively before expires_in runs out, and recovers once if a token is rejected early.

# oauth_client_credentials.py
import time
import requests

class OAuth2Client:
    def __init__(self, token_url, client_id, client_secret, scope=None):
        self.token_url = token_url
        self.client_id = client_id
        self.client_secret = client_secret
        self.scope = scope
        self.session = requests.Session()
        self._expires_at = 0.0

    def _fetch_token(self):
        data = {"grant_type": "client_credentials"}
        if self.scope:
            data["scope"] = self.scope
        # Confidential clients authenticate with HTTP Basic (RFC 6749 §2.3.1).
        r = self.session.post(
            self.token_url, data=data,
            auth=(self.client_id, self.client_secret), timeout=10,
        )
        r.raise_for_status()
        tok = r.json()
        # Refresh ~60s early; fall back to 1h if the server omits expires_in.
        self._expires_at = time.time() + tok.get("expires_in", 3600) - 60
        self.session.headers["Authorization"] = f"Bearer {tok['access_token']}"

    def _ensure_token(self):
        if time.time() >= self._expires_at:
            self._fetch_token()

    def get(self, url, **kwargs):
        self._ensure_token()
        r = self.session.get(url, timeout=10, **kwargs)
        if r.status_code == 401:          # rejected early → fetch once and retry
            self._fetch_token()
            r = self.session.get(url, timeout=10, **kwargs)
        r.raise_for_status()
        return r.json()

Driving proactive refresh off expires_in rather than waiting for a 401 means the common path never incurs a failed request, and the 401 branch catches the rare case of a token revoked or invalidated ahead of schedule.

The refresh-token flow

When a grant does issue a refresh token, you exchange it for a fresh access token with grant_type=refresh_token (RFC 6749 §6), authenticating the request with the same client ID and secret:

def refresh_access_token(session, token_url, client_id, client_secret, refresh_token):
    data = {"grant_type": "refresh_token", "refresh_token": refresh_token}
    # Some providers (e.g. Webex) want client_id/client_secret in the body instead of Basic.
    r = session.post(token_url, data=data,
                     auth=(client_id, client_secret), timeout=10)
    r.raise_for_status()
    tok = r.json()
    new_access = tok["access_token"]
    new_refresh = tok.get("refresh_token", refresh_token)  # server MAY rotate it
    return new_access, new_refresh, tok.get("expires_in", 3600)

Two details catch people out. First, the server may return a new refresh token — if it does, persist it and discard the old one, or your next refresh fails. Second, because the request needs the client secret as well as the refresh token, a leaked refresh token alone is not enough to mint tokens, which is why providers can afford to give it a long lifetime.

Operational habits

  • Refresh proactively, recover reactively. Schedule against expires_in with a little headroom, and keep a single 401-triggered refresh-and-retry as the safety net.
  • Serialize refresh across threads. If you fan work out (see Scaling with concurrency), many workers can hit expiry at once and stampede the token endpoint. Guard the refresh with a threading.Lock and re-check expiry inside it, so only the first thread refreshes and the rest reuse the new token.
  • Store secrets, not tokens, durably. The client secret and any refresh token are the long-lived secrets — keep them in a vault or environment variable, never in Git. Hold access tokens in memory; they expire on their own.
  • Ask for the narrowest scope. Request only the permissions the job needs, and read the returned scope — the server may have granted less than you asked for.
  • Mind clock skew. Proactive refresh depends on your host's clock; a badly skewed clock can refresh constantly or too late. Keep NTP healthy.

Key takeaways

  • OAuth 2.0 trades a static key for short-lived access tokens, limiting the blast radius of a leak and letting durable credentials be scoped and revoked independently.
  • Use the client credentials grant for headless machine-to-machine automation — no user, no refresh token; just request a new access token when the old one expires.
  • Use refresh tokens when the grant issues them (user-delegated integrations such as Webex), and persist a rotated refresh token when the server returns one.
  • Drive refresh off expires_in proactively, keep a single 401 retry as a fallback, and serialize refresh so concurrent workers don't stampede the token endpoint.
  • Treat the access token as a secret in transit, store only the durable credentials, and request the narrowest scope that works.

Sources: RFC 6749 — The OAuth 2.0 Authorization Framework (§4.4 client credentials, §5.1 token response, §6 refreshing a token), Webex — Integrations & Authorization, Webex — Service Apps.