Free tech learning for everyone, from basics to pro

APIsProgramming and Application SecurityIntermediate

API authentication: API keys, basic auth, OAuth 2.0 and JWTs

In short: APIs authenticate callers with static keys, usernames and passwords, short-lived tokens or certificates. OAuth 2.0 issues scoped access tokens, often in JWT format, so scripts never need a user’s password. Whatever the method, keep secrets out of code, use HTTPS, and give each token the least privilege it needs.

Authentication vs authorisation

Authentication answers who you are. Authorisation answers what you are allowed to do. An API normally does both on every request: it checks the credential, then checks whether that identity may perform this method on this resource. Remember the status codes: 401 for failed authentication, 403 for failed authorisation.

API authentication methodsAPI keystatic secret headerBasic authuser:pass, base64Session tokenlogin, then reuseOAuth 2.0delegated accessJWTsigned token formatmTLSclient certificate
Figure 1. Six common ways an API decides who is calling, from simple static keys to certificate-based mutual TLS.

Simple methods: API keys and basic auth

An API key is a long random string the provider gives you. You send it in a header such as X-API-Key or Authorization. Keys are easy to use but usually do not expire on their own, so a leaked key stays useful to an attacker until someone revokes it.

Basic authentication sends username:password encoded in Base64 in the Authorization header. Base64 is encoding, not encryption; anyone can reverse it (try the Base64 tool). Basic auth is only acceptable over HTTPS, and many platforms now use it just to obtain a token on first login.

export NMS_TOKEN="$(cat ~/.secrets/nms_token)"   # or use a secrets manager
curl -s -H "Authorization: Bearer $NMS_TOKEN" \
     -H "Accept: application/json" \
     https://nms.example.com/api/v1/devices

OAuth 2.0 and its flows

OAuth 2.0 is a framework for issuing access tokens. Instead of sharing a password with every application, an authorisation server issues tokens that are short-lived and limited by scopes such as devices.read. The two flows you will meet most:

  • Client credentials: for machine-to-machine work such as an automation script. The script authenticates as itself with a client ID and secret (or a certificate) and receives a token.
  • Authorisation code with PKCE (Proof Key for Code Exchange): for apps acting on behalf of a signed-in user. The user logs in at the identity provider, never giving the app their password.

Older flows such as the implicit grant and the resource owner password grant are discouraged in current guidance, including the OAuth 2.0 Security Best Current Practice (RFC 9700). OpenID Connect (OIDC) builds on OAuth 2.0 to add a standard way of proving the user’s identity.

OAuth 2.0 client credentials flowScripthas client ID+ secretAuth serverPOST /tokenAccess tokenshort-lived,scopedAPI callBearer tokenAPI checkssignature,scope, expiry
Figure 2. In the client credentials flow a script swaps its own credentials for a short-lived access token, then uses that token on each call.

JSON Web Tokens

A JWT (JSON Web Token) is a common format for access tokens. It has three Base64url parts separated by dots: a header (which algorithm), a payload of claims (issuer, subject, audience, expiry, scopes) and a signature. The signature proves the token was issued by a trusted party and has not been changed. It does not hide the contents, so never put secrets in a JWT payload.

An API that accepts JWTs must check: the signature with the expected algorithm and key, the issuer (iss), the audience (aud), and the expiry (exp). Classic mistakes include accepting the none algorithm, letting the token choose its own algorithm, and skipping the audience check.

import jwt   # pip install PyJWT

claims = jwt.decode(
    token,
    key=public_key,
    algorithms=["RS256"],          # fixed list, never from the token
    audience="https://api.example.com",
    issuer="https://login.example.com/",
)

Storing and handling secrets

DoDo not
Read secrets from environment variables or a vaultHard-code them in scripts
Add .env files to .gitignoreCommit keys to Git, even private repos
Use separate read-only and read-write tokensUse one admin key everywhere
Rotate and set expiry datesLeave keys valid for years
Prefer short-lived OAuth tokens or mTLSSend secrets in URLs

Tip: if a key ever lands in a Git commit, deleting the file is not enough. Revoke the key at the provider straight away, then clean the history.

Practice

Why is basic authentication over plain HTTP unsafe?
The credentials are only Base64-encoded, not encrypted, so anyone who sees the traffic can decode the username and password.
Which OAuth 2.0 flow suits a nightly backup script with no user present?
The client credentials flow, where the script authenticates as itself and receives a scoped access token.
Name three claims an API should check in a JWT besides the signature.
Issuer (iss), audience (aud) and expiry (exp); scopes or roles should also be checked for authorisation.

Key takeaways

  • Authentication proves identity; authorisation decides what is allowed.
  • API keys and basic auth are simple but long-lived; always use HTTPS.
  • OAuth 2.0 issues short-lived, scoped tokens; use client credentials for scripts.
  • JWTs are signed, not encrypted; validate algorithm, iss, aud and exp.
  • Keep secrets out of code and Git, and give each token least privilege.
Tracks your learning on this device only. See your progress on the learning paths.

About the author

Mohamed Fayas

Founder of FM TecHub. CCNA certified, with a BTEC HND in Network Engineering, and BEng (Hons) in Computer Networking and Cloud Security. He writes practical, plain-English guides on networking, security and cloud.

More about the author

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Stay up to date by email

New notes, tools and security news from FM TecHub, explained simply. Free.

We only use your email to send these updates. See our privacy policy.