What is an API token?
An API token lets your app call an API on a user's behalf without handing over a password or a master key. Here's how tokens work, how they differ from API keys, and how to keep them from leaking.
API token vs API key at a glance
|
API token |
API key | |
|---|---|---|
|
Identifies |
A user, session or service acting on someone's behalf |
An application or project |
|
How you get it |
Issued after a login or OAuth flow, or by your server |
Generated once in a provider's dashboard |
|
Lifetime |
Minutes to days; expires by design |
Long-lived until someone rotates it |
|
Permissions |
Scoped to what that user or task needs |
Often full access to the project |
|
Where it's used |
Client apps and server calls made for a user |
Server-to-server calls |
|
Format |
Opaque string or a JWT |
Random string |
|
Revocation |
Expire or revoke one token |
Rotate the key, which breaks every caller using it |
|
If it leaks |
Damage limited by scope and expiry |
Broad access until rotated |
What an API token does
An API needs to answer two questions on every request: who is this, and are they allowed to do this? An API token answers both without the caller sending a password each time.
You'll see a few kinds:
Access tokens are short-lived tokens issued after sign-in, often through OAuth 2.0. They carry the caller's permissions, called scopes.
Refresh tokens last longer and exist only to get a new access token when the old one expires. They never go to the API itself.
Personal access tokens are created by a developer in a dashboard (GitHub is the familiar example) for scripts and CI jobs. They behave more like API keys, so give them an expiry date.
Service tokens are issued to a backend service rather than a person, for calls between your own systems.
A token can be an opaque random string that the API looks up in its database, or a self-contained JWT that the API can verify by checking its signature.
How API tokens work
A typical flow for an app that talks to a third-party API looks like this:
The user signs in to your app the normal way.
Your server, which holds the secret API key, asks the API provider for a token for that user.
The provider returns a short-lived token tied to that user and their permissions.
Your server passes the token to the client app.
The client sends the token with every request in the
Authorization: Bearer <token>header, as defined in RFC 6750.
When the token expires, the API replies 401 Unauthorized and the client asks your server for a new one. The secret key never reaches the browser or the phone, so pulling apart your app bundle gets an attacker nothing reusable.
Example: calling an API with a bearer token
The client side is short. The token goes in a header, never in the URL, because URLs end up in server logs, browser history and analytics tools.
// Fetch messages with a bearer token and handle expiry
async function getMessages(token) {
const res = await fetch("https://api.example.com/v1/messages", {
headers: { Authorization: `Bearer ${token}` },
});
if (res.status === 401) {
// Token expired or was revoked: ask your server for a new one
throw new Error("Unauthorized: refresh the token and retry");
}
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
On the server, the API validates the token on each request: it checks that the token exists or that its signature is valid, that it hasn't expired, and that its scopes cover the action being asked for.
Rule of thumb: if a credential can do everything and never expires, it belongs on your server. If it has to live on a user's device, make it short-lived and scoped to that user.
API token security best practices
Keep secrets on the server. Anything shipped in a web or mobile app can be extracted. Only short-lived, user-scoped tokens belong on the client.
Set short expiry times. Minutes to an hour for access tokens is common. Use refresh tokens or a server call to get new ones.
Grant the smallest scope that works. A token for reading messages shouldn't be able to delete users.
Send tokens over HTTPS only, in the
Authorizationheader, never in query strings.Store them carefully. In browsers, an HttpOnly, Secure cookie or in-memory storage is safer than
localStorage, which any injected script can read. On mobile, use the Keychain (iOS) or Keystore (Android).Make revocation possible. Logging out, changing a password or removing a user should kill their tokens.
Keep tokens out of logs and error reports, and scan your repositories for committed tokens.
Limits and pitfalls
The bearer gets in. Anyone holding a valid bearer token can use it. That's why expiry and scope matter more than the token format.
The names are used loosely. Some providers call a long-lived secret an "API token" and a scoped credential an "API key". Judge a credential by its lifetime and permissions, not its label.
Self-contained tokens are hard to recall. A JWT stays valid until it expires unless the API also checks a revocation list. Keep lifetimes short.
Expired tokens break quietly. If the client doesn't handle
401responses and fetch a new token, users get stuck on empty screens.Tokens don't replace rate limits. A leaked or misused token can still hammer an API, so pair tokens with rate limiting.
How CometChat handles user tokens
CometChat follows the same pattern, so your secret keys stay on your server and each user gets their own credential.
Secret key on your server, auth token on the device
Your server creates each user in CometChat and requests an auth token for them with the Create Auth Token endpoint (
POST /v3/users/{uid}/auth_tokens), authenticated with your REST API key. Your app passes that token toCometChat.login(authToken), and the SDK keeps the session from there. The Auth Key that ships with sample apps is for prototypes only, so it never belongs in production client code.
Frequently asked questions
What is the difference between an API key and an API token?
An API key usually identifies an application and lives for a long time, so it belongs on a server. An API token usually represents a user or session, carries limited permissions and expires, so it's safer to hand to a client app.
Where do I put an API token in a request?
In the Authorization header, as Authorization: Bearer followed by the token. Avoid putting tokens in URLs, because URLs are stored in logs and browser history.
How long should an API token last?
Access tokens commonly last between a few minutes and an hour. Refresh tokens and personal access tokens last longer, but they should still have an expiry date and be revocable.
Is a JWT an API token?
It can be. JWT is a token format, and many APIs issue access tokens as JWTs. Other APIs use opaque random strings that they look up in a database. Both work as bearer tokens.
What should I do if an API token leaks?
Revoke it straight away, issue a new one, and check your logs for calls made with it. Short expiry times and narrow scopes limit what a leaked token can do.