Developer & Network Tools

API Keys, Tokens and OAuth

Understand how API keys, access tokens and OAuth differ, when to use each, and how to store and revoke credentials safely.

Key takeaways

  • API keys are simple long-lived secrets that mainly identify the calling project or account.
  • OAuth 2.0 lets a user grant limited, revocable access to an app without sharing a password.
  • Access tokens carry the permission; refresh tokens obtain new ones and need stronger protection.
  • OAuth by itself is about authorization, and OpenID Connect adds a standard way to sign users in.
  • Any secret shipped inside a web page or mobile app should be assumed readable by others.

An API key identifies an application or account and usually lasts until someone revokes it. An access token is a credential, typically short-lived, that grants specific permissions. OAuth is a standard way for a user to let one application act on their behalf at another service without handing over their password.

Which one you meet depends on the question the service needs answered. "Which program is calling?" is often handled by a key. "May this program read this particular person's calendar?" is what OAuth was designed for.

API keys

An API key is a long random string the provider generates for you. You send it with each request, usually in a header:

curl https://api.example.com/v1/reports \
  -H "Authorization: Bearer YOUR_API_KEY"

Some providers use a custom header such as X-API-Key. A few accept keys in the query string, but URLs get recorded in server logs and browser history, so prefer a header when you have the choice.

Keys are easy to use and easy to leak. Anyone holding one can act as you until it's revoked. Better providers let you restrict a key to certain operations, source addresses or websites, set an expiry date, and issue separate keys for testing and production.

Tokens and bearer credentials

"Token" is a broad word for a credential that stands in for a login. A bearer token works for whoever presents it, the way a cinema ticket does. RFC 6750 describes how bearer tokens are used with OAuth 2.0.

Tokens come in two broad forms. An opaque token is a random reference that the server looks up. A self-contained token carries claims inside it with a signature, so a service can check it without a lookup. The best-known format is covered in JSON Web Tokens explained.

Short lifetimes limit the damage from theft. A token that expires within minutes or hours is far less useful to someone who finds it in an old log file than a key that never expires.

What problem OAuth solves

Imagine a photo printing site that wants pictures from your cloud album. The bad old method was to type your album password into the printing site, which then had full control and could keep it.

OAuth replaces that. You're sent to the album service itself, you sign in there, and you approve a specific request such as "view your photos". The printing site receives a token limited to that, and you can revoke it later without changing your password. The core framework is OAuth 2.0, published as RFC 6749.

It defines four roles:

  • Resource owner: you, the person who owns the data.
  • Client: the app asking for access.
  • Authorization server: the system that signs you in and issues tokens.
  • Resource server: the API that holds the data and accepts tokens.

The authorization code flow

The most common flow for apps with a user involves a one-time code and an extension called PKCE (RFC 7636, pronounced "pixy").

OAuth authorization code flow with PKCE
You App Authorization server API Choose to connect 1 Send you over with scopes 2 plus a PKCE challenge Sign in and approve 3 One-time code 4 Code plus PKCE verifier 5 Access token 6 Request with token 7 You App Authorizati on server API Choose to connect 1 Send you over with scopes 2 plus a PKCE challenge Sign in and approve 3 One-time code 4 Code plus PKCE verifier 5 Access token 6 Request with token 7

The app first creates a random secret (the verifier) and sends only a hash of it (the challenge). When it later trades the code for a token, it reveals the verifier. Someone who intercepts the code alone can't use it. The app also sends or checks values that tie the response to the request it started, such as the state parameter, to resist forged callbacks.

Other flows serve other situations. In the client credentials grant, a server authenticates as itself with no user involved. The device authorization grant (RFC 8628) covers TVs and tools without a convenient keyboard: you enter a short code on your phone. Older flows that returned tokens directly in the browser address, or collected your password in the app, are discouraged by current security guidance.

Scopes, refresh tokens and revocation

Scopes are named permissions, such as photos.read. An app should request the narrowest set that does the job, and a user should be suspicious when a simple tool asks to read and send all mail. Attackers abuse exactly this in consent phishing.

A refresh token lets the app obtain new access tokens without asking you again. Because it can live a long time, it belongs only in secure storage. Many authorization servers replace it on each use and cancel the whole chain if an old one reappears.

Both you and the provider can revoke access. Most large services have a settings page listing connected apps, and it's worth reviewing occasionally.

Signing in is a different job

OAuth answers "what may this app do?" It wasn't designed to tell the app who you are. OpenID Connect is a layer on top that adds an ID token with verified claims about the user, and it underlies many "sign in with" buttons. The wider picture is in single sign-on and sign-in buttons.

Which credential answers which need
API key A script or server identifying your account. Client credentials Service to service, no person involved. OAuth user grant An app acting on a user's data with consent. OpenID Connect Learning who just signed in. API key A script or server identifying your account. Client credentials Service to service, no person involved. OAuth user grant An app acting on a user's data with consent. OpenID Connect Learning who just signed in.

Storing and handling secrets

Most credential trouble comes from handling, not from cryptography.

  1. Keep secrets in environment variables or a secrets manager, as described in environment variables and secrets.
  2. Exclude local secret files from version control, and turn on secret scanning if your code host offers it.
  3. Never embed a private key or client secret in browser code or a distributed app. People can extract it. Call the provider from your own server instead.
  4. Use separate credentials per application and environment, so revoking one doesn't break everything.
  5. Redact authorization headers from logs, bug reports and screenshots.
  6. Rotate on a schedule and immediately after any suspected leak or staff departure.

If a secret has been committed or posted, deleting the file isn't enough. Revoke the credential, issue a new one, and check the provider's usage logs for activity you don't recognize.

Where browsers and mobile apps fit

A server can keep a secret. An app running on someone else's device mostly can't, and OAuth calls the first kind a confidential client and the second a public client.

For public clients, PKCE protects the code exchange, and the authorization server only returns codes to redirect addresses registered in advance. Mobile apps should open the sign-in page in the system browser, not in a web view the app controls, so the app never sees your password and you can check the address you're typing into.

Web applications have a further choice. One design keeps tokens entirely on the web server and gives the browser an ordinary session cookie marked HttpOnly and Secure, which page scripts can't read. This is often called the backend-for-frontend pattern. The alternative, storing tokens where JavaScript can reach them, means any script injection flaw can take them. How cookies work in HTTP explains those flags.

Stronger options for sensitive systems

Bearer tokens have an obvious weakness: whoever copies one can use it. Some systems bind a token to a key the client holds, so a stolen copy is useless alone. Mutual TLS, where the client also presents a certificate, is one method. DPoP, defined in RFC 9449, is another, in which the client signs a small proof for each request.

Cloud platforms offer a different improvement for server workloads: the platform gives a running service a temporary identity, and short-lived credentials are issued automatically. Nothing long-lived needs to be written into a configuration file at all. If your hosting supports this, it removes a whole category of leaked-key incidents.

These add moving parts. For a hobby script reading public data, a restricted key kept out of the repository is proportionate. For anything touching money, health or other people's accounts, the extra protection is worth the setup.

Reviewing access as a user

You don't need to be a developer for any of this to matter. Each time you approve a connection, a third party gains standing access that survives long after you've forgotten the app. Read the consent screen: check the app's name, who publishes it and what it asks for. Refuse requests that don't match the purpose, and remove connections you no longer use. Changing your password doesn't necessarily cancel tokens already issued, so use the connected-apps page to revoke them directly.

When requests are refused

A 401 response generally means the credential is missing, malformed or expired. A 403 means you're identified but not allowed, often because a scope or role is missing. The difference is explained in 403 vs. 401.

Check that you're using the right environment's credential, that the header format matches the documentation exactly, that no stray space or newline was copied, and that the server's clock is accurate if tokens have time limits. Avoid pasting live tokens into websites to inspect them. A token is a working credential until it expires, so test with throwaway ones and treat real ones like passwords.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Developer & Network Tools →

Latest news on this topic