Every time an app loads a map, sends a message, or fetches your profile, it is talking to an API behind the scenes. Most of the time we treat that request-response loop like magic. But if you stop and think about it, HTTP itself has no memory. Every request arrives at the server as a stranger.
So how does an API actually know you are you, and how does it decide what you are allowed to touch?
This post is the written version of a talk I gave last year breaking down API authentication from first principles: what the common methods actually look like on the wire, where each one shines, and the mistakes that still trip up real apps.
What an API is and why auth matters
An API (Application Programming Interface) is simply a contract that lets one piece of software use the data or capabilities of another over well-defined endpoints and protocols. Good APIs are modular, reusable, and scalable, which is exactly why almost every modern app depends on them.
That openness is also what makes security non-negotiable. Without proper authentication and access control, an API cannot:
- Protect sensitive data: Keep personal or private records out of unauthorized hands.
- Confirm identity: Verify that a user or client is really who it claims to be before serving data.
- Prevent abuse: Stop bots, scrapers, and spammers with rate limits and per-client controls.
- Enforce permissions: Apply clear rules on who can read, create, update, or delete resources.
Authentication vs. Authorization
People mix these two up all the time, even though they answer two completely different questions:
- Authentication (AuthN) asks: “Who are you?”
- Authorization (AuthZ) asks: “What are you allowed to do?”
The easiest way to remember the difference is a university campus. Swiping your student ID at the front gate to get inside is authentication: you proved who you are. Walking up to the faculty elevator and tapping that same card only to get rejected because you are not staff or a professor is authorization: the system knows who you are, it just says you do not have permission to use that elevator.
Authentication always comes first. Once the server knows your identity, authorization models like RBAC (Role-Based Access Control, such as admin vs. user) or ABAC (Attribute-Based Access Control, checking rules like department, time, or resource owner) decide whether the request goes through.
Common API authentication methods
There is no single “best” auth method. Each one is a trade-off between simplicity, security, and operational overhead.
1. API Keys and HMAC
An API key is a unique string issued to a client or user and sent with every request, usually in a header or query parameter:
GET /v1/weather?city=istanbul HTTP/1.1
Host: api.example.com
X-API-Key: sk_example_8fba4c4b6d1e4f2a3bAPI keys are dead simple to implement and great for tracking usage or applying rate limits. The catch is that they are static secrets. If a key leaks in a public repository or client-side bundle, anyone who grabs it can impersonate you until you rotate it.
When you need stronger guarantees that a request was not tampered with in transit, HMAC (Hash-based Message Authentication Code) steps in. Both the client and server share a secret key. For every request, the client hashes the request details (method, path, timestamp, body) with that secret using a hash function like SHA-256 and attaches the signature:
POST /v1/orders HTTP/1.1
Host: api.example.com
X-Timestamp: 1751625600
X-Signature: sha256=3b91f4c8e2a7d901c4b2f6e8a1d3c5e7...The server recalculates the hash on its end. If the signatures match, the request is both authentic and unmodified. It is much stronger than a plain API key, at the cost of extra implementation complexity on both sides.
2. Basic Auth
Basic Authentication is one of the oldest and simplest HTTP auth schemes. The client combines username:password, encodes it in Base64, and sends it in the Authorization header on every request:
GET /v1/account HTTP/1.1
Host: api.example.com
Authorization: Basic c2V6ZXI6c3VwZXJzZWNyZXQ=The server decodes the string and checks it against its user database.
The critical thing to remember here: Base64 is encoding, not encryption. Anyone who intercepts c2V6ZXI6c3VwZXJzZWNyZXQ= can decode it back to sezer:supersecret in one second. Basic Auth is fine for quick internal tools or scripts, as long as it is strictly wrapped in HTTPS.
3. JSON Web Tokens (JWT)
A JWT (RFC 7519) is a compact, URL-safe, self-contained token made of three dot-separated Base64URL parts: header.payload.signature.
- Header: The token type and signing algorithm (for example,
HS256orRS256). - Payload: Claims about the user, like
sub(user ID),role, andexp(expiration time). - Signature: A cryptographic signature created with the server’s secret or private key so nobody can forge or alter the payload.
{
"sub": "user_42",
"role": "member",
"iat": 1751625600,
"exp": 1751629200
}A typical JWT flow looks like this:
- The user logs in with their credentials.
- The server verifies them, signs a JWT, and returns it to the client.
- The client stores the token (ideally in an
HttpOnlycookie, notlocalStorage). - On each API call, the client sends
Authorization: Bearer <token>(or the browser sends the cookie automatically). - The server checks the token’s signature and expiration.
- If everything checks out, access is granted without looking up a session table in the database.
That statelessness is why JWTs are everywhere in REST APIs, SPAs, and mobile apps: they scale easily across multiple servers and cut down session lookups. The flip side is revocation. Because the server does not track active tokens by default, invalidating a leaked or long-lived JWT before it expires is awkward. Keep access tokens short-lived, and remember that the payload is only encoded, not encrypted, so never put secrets inside it.
4. OAuth 2.0
OAuth 2.0 (RFC 6749) solves a different problem: delegated authorization. Instead of handing your Google or GitHub password to a third-party app so it can read your calendar or repos, OAuth 2.0 lets you log in directly with the trusted provider and approve a specific set of permissions (scopes).
The provider then hands the third-party app a limited, time-bound access token. You get three big wins:
- Your actual password is never shared with the app.
- Access is tightly scoped (for example, “read profile only” instead of full account control).
- Tokens can expire or be revoked from the provider’s settings at any time.
It is the backbone of modern web and mobile logins, though its full spec and grant flows can easily be overkill for a small internal API.
Comparing the methods at a glance
| Method | How it works | Pros | Cons |
|---|---|---|---|
| API Keys | Static unique string sent per client | Simple to set up, great for usage tracking | No built-in expiry; anyone with a leaked key has access |
| HMAC | Client signs each request with a shared-secret hash | Strong integrity, prevents request tampering | Harder to implement and debug correctly |
| Basic Auth | Authorization: Basic <Base64(user:pass)> | Built into HTTP, effortless to test | Base64 is trivially reversible; unsafe without HTTPS |
| JWT | Signed, self-contained header.payload.signature token | Stateless, carries identity claims, scales cleanly | Hard to revoke early; risky if stored poorly |
| OAuth 2.0 | Delegated token flows via trusted identity providers | Scoped permissions, no password sharing | Complex protocol, overkill for simple APIs |
Four common mistakes to avoid
Picking a modern standard like JWT or OAuth 2.0 does not automatically make an API secure. Most real-world breaches come from small implementation mistakes:
- Storing sensitive tokens in
localStorage: Any JavaScript running on the page can readlocalStorage. If your app has even one XSS vulnerability, an attacker can steal the token immediately. PreferHttpOnly,Secure,SameSitecookies for sensitive tokens. - Not validating JWT signatures: Decoding a JWT payload without verifying its signature (or accepting the insecure
"alg": "none"header) lets an attacker edit"role": "user"to"role": "admin"and walk right in. Always verify the signature and algorithm server-side using a well-tested library. - Exposing API keys in frontend code or Git: Any key shipped in client-side JavaScript is public. Keep private keys strictly on the backend, load them from environment variables, and never commit
.envfiles to version control. - Skipping HTTPS: Sending credentials, API keys, or bearer tokens over plain HTTP leaves them completely exposed to man-in-the-middle attacks on the network. Encrypt everything in transit with TLS, no exceptions.
Wrapping up
Authentication and authorization are rarely the flashiest part of building a product, but getting them right is what keeps everything else standing. Start with the simplest method that fits your threat model: an API key or HMAC for server-to-server calls, short-lived JWTs or cookies for your own app sessions, and OAuth 2.0 when delegating access across services.