API AUTHENTICATION LEARNING GUIDE

API, Tokens, and JWT Authentication

Understand how applications prove identity, receive access tokens, call protected APIs, validate JWTs, refresh sessions, and avoid common security mistakes.

API keysBearer tokensJWT claimsAccess and refresh tokens
Client App
Bearer token
eyJhbGciOi...
Protected API
Authorized
START HERE

API authentication in three concepts

These terms are related, but they do not mean the same thing.

01

API

An API is a contract that lets one application request data or actions from another. Public endpoints may be open, while protected endpoints require proof of identity or permission.

GET /api/orders/1042
02

Token

A token is a credential issued after an authentication or authorization step. The client sends it with later requests instead of repeatedly sending a password.

Authorization: Bearer <token>
03

JWT

A JWT is one possible token format. It carries signed claims in three dot-separated segments. Access tokens may be JWTs, but they can also be opaque values.

header.payload.signature
REQUEST LIFECYCLE

How token-based API authentication works

A common sign-in and protected API request, from the first credential check to the final response.

  1. 1

    User signs in

    The app sends credentials or starts an external identity-provider flow.

  2. 2

    Identity is verified

    The authorization server checks the user, client, and requested permissions.

  3. 3

    Tokens are issued

    The client receives a short-lived access token and, when appropriate, a refresh token.

  4. 4

    Client calls the API

    The access token is sent in the Authorization header over HTTPS.

  5. 5

    API validates access

    The API verifies token integrity, claims, expiry, audience, and required permission.

  6. 6

    Response is returned

    The API returns data, or a clear 401/403 response when access is not valid.

401 UnauthorizedAuthentication is missing, expired, or invalid.
403 ForbiddenThe caller is known but lacks permission for the action.
INTERACTIVE DEMONSTRATION

Explore the three parts of a JWT

Select a colored segment to see what it contains and what the API must verify.

..
Payload

Contains claims about the subject, issuer, audience, roles, issue time, and expiration.

{ "sub": "user-1042", "role": "admin", "exp": 1783000000 }

Security note: A normal JWT payload is encoded, not encrypted. Do not place passwords, secrets, or private personal data here.

Base64URL makes JWT segments URL-safe and readable. It does not hide the data. Learn how Base64 encoding works or inspect a token in the JWT Decoder.

CHOOSE THE RIGHT CREDENTIAL

API key, access token, refresh token, and ID token

Each credential has a different audience and lifecycle. They should not be used interchangeably.

CredentialMain purposeSent toTypical lifetimeImportant rule
API keyIdentify an application or projectTarget APILonger livedRestrict by service, origin, IP, or quota where possible.
Access tokenAuthorize API operationsResource APIShort livedUse scopes and send only to its intended audience.
Refresh tokenObtain a new access tokenAuthorization serverLonger livedNever send it to normal resource API endpoints.
ID tokenTell a client about an authenticated userClient applicationShort livedDo not use it as an API access token.
THE QUESTIONS USERS ACTUALLY ASK

How does logout work, and why do apps keep me signed in for days?

Long-lived sign-in is usually a managed session, not one access token that remains valid forever. The application combines short-lived access tokens with a protected refresh token or server session.

How does logout work?

The app removes its local session, clears authentication cookies or stored credentials, and may revoke the refresh token on the authorization server. Already-issued access tokens can remain valid until they expire unless the system also checks a revocation list or session version.

Why do Instagram, Facebook, and other apps stay signed in?

Large applications commonly keep a durable device session in secure storage. When a short-lived access token expires, the app silently requests a replacement, so the user does not need to enter a password every hour. Exact implementations differ by service.

1User signs in oncePassword, passkey, or identity provider
2Access tokenShort life; sent to the API
3Token expiresAPI returns 401 or client refreshes early
4Refresh securelyAuthorization server issues a new access token

What a refresh token does

A refresh token proves that an existing session may request another access token. It is sent only to the authorization server, never to ordinary business API endpoints.

Refresh-token rotation

On every refresh, the server issues a replacement refresh token and invalidates the previous one. Reuse of an old token can reveal theft and trigger revocation of the token family.

Sliding and absolute expiry

A sliding window extends an active session, while an absolute limit forces sign-in after a maximum period. Using both prevents a session from silently lasting forever.

Browser and mobile storage

Browser applications often use Secure, HttpOnly, SameSite cookies or a backend-for-frontend. Mobile apps should use platform-protected keychain or keystore storage.

Logout on this device

Clear the local cookie or stored session and revoke that device's refresh token.

Logout from all devices

Revoke all refresh-token families or increment a server-side session version for the account.

Password changed or account disabled

Revoke active sessions and require recent authentication for sensitive operations.

Lost or stolen device

Let the user review sessions, remove the device, and invalidate its refresh credentials remotely.

PRACTICAL EXAMPLES

Send and validate a Bearer access token

The same HTTP header works across tools and languages; secure validation belongs on the API.

HTTP

Raw API request

GET /api/orders/1042 HTTP/1.1
Host: api.example.com
Authorization: Bearer ACCESS_TOKEN
Accept: application/json
JS

JavaScript fetch

const response = await fetch(url, {
  headers: {
    Authorization: `Bearer ${accessToken}`
  }
});
C#

ASP.NET Core API

builder.Services
  .AddAuthentication("Bearer")
  .AddJwtBearer(options => {
    // Validate issuer, audience and key
  });

app.UseAuthentication();
app.UseAuthorization();

REAL-WORLD SCENARIOS

Which token pattern fits the situation?

Browser application

User signs in and calls an API

Use a standards-based authorization flow. Keep access tokens short lived and choose browser storage based on XSS, CSRF, and deployment architecture.

Mobile application

Persistent sign-in across sessions

Use system browser authorization and platform-secure storage. Rotate refresh tokens and support revocation when a device is lost.

Service to service

A background process calls another API

Use a workload identity or client credentials flow. Grant only the scopes required by that service and rotate credentials.

Third-party integration

A customer connects an external service

Use delegated authorization instead of collecting the customer's password. Clearly display requested permissions and support disconnecting access.

SECURITY CHECKLIST

Validate more than the signature

  • Require HTTPS for every token exchange and protected API call.
  • Allow only the expected signing algorithms and trusted keys.
  • Validate issuer, audience, expiration, and not-before claims.
  • Use short-lived access tokens and narrowly defined scopes.
  • Keep refresh tokens out of logs and normal API requests.
  • Return 401 for invalid authentication and 403 for denied permission.
COMMON MISTAKES

Patterns that create avoidable risk

  • Putting passwords, secrets, or sensitive personal data in JWT claims.
  • Treating a decoded token as verified or trusted.
  • Accepting any issuer, audience, or signing algorithm.
  • Using an ID token to authorize a resource API.
  • Sending tokens in URLs where logs and history may capture them.
  • Giving every user or service broad administrator permissions.
FREQUENTLY ASKED QUESTIONS

API token and JWT questions

Clear answers to common implementation and security questions.

What is an API token?

An API token is a credential sent with an API request to identify or authorize a user, application, or service. Its exact format depends on the authentication system.

What is the difference between an API key and an access token?

An API key commonly identifies an application or project. An access token usually represents delegated access for a user or service and often has scopes and an expiration time.

Is every access token a JWT?

No. An access token can be a JWT or an opaque random value. Clients should normally treat access tokens as strings unless the authorization system explicitly documents their format.

What does Bearer token mean?

A bearer token can be used by whoever possesses it. It must therefore be protected in transit, logs, browser storage, and application code.

Can a JWT payload be decoded without a secret key?

Yes. JWT header and payload segments are usually Base64URL encoded and can be decoded without a key. A key is needed to create or verify the signature, depending on the signing algorithm.

Does decoding a JWT prove that it is valid?

No. Decoding only reveals readable content. Validation must also verify the signature, issuer, audience, expiration, not-before time, and other application rules.

What is the difference between an access token and a refresh token?

An access token is sent to an API and should be short lived. A refresh token is sent only to the authorization server to obtain a new access token and normally requires stronger protection.

How does logout work with JWT access tokens?

Logout normally clears the local session and revokes the refresh token. A previously issued JWT access token may remain valid until its short expiration time unless the API also uses server-side revocation or session-version checks.

Why do apps keep me logged in for days or weeks?

Many apps keep a protected device session or refresh token. They silently obtain new short-lived access tokens while the session remains trusted, subject to inactivity limits, absolute expiry, risk checks, and user revocation.

What is refresh token rotation?

Refresh token rotation replaces the refresh token every time it is used and invalidates the previous value. Reuse of an invalidated token can indicate theft and may revoke the complete token family.

Can a refresh token be a JWT?

It can be, but it does not have to be. Many systems use opaque random refresh tokens because clients should treat refresh tokens as secrets and should not depend on their internal format.

Where should a refresh token be stored?

Browser applications commonly use Secure, HttpOnly, SameSite cookies or a backend-for-frontend pattern. Native mobile applications should use platform-secure keychain or keystore storage.

How does logout from all devices work?

The server revokes every refresh-token family or invalidates a server-side session version for the account. Short-lived access tokens then expire naturally or are rejected by an additional server-side session check.

Should I store JWT tokens in localStorage?

There is no universal answer. localStorage is accessible to JavaScript and therefore exposed during an XSS attack. Secure, HttpOnly, SameSite cookies are often preferred for browser sessions, depending on the architecture and CSRF controls.

What are JWT claims?

Claims are values in the JWT payload. Registered claims include iss, sub, aud, exp, nbf, iat, and jti. Applications may also define private claims such as roles or permissions.

How is a token sent to an API?

A common pattern is the HTTP Authorization header using the Bearer scheme: Authorization: Bearer followed by the access token.

What should an API validate in a JWT?

The API should verify the cryptographic signature and validate the expected issuer, audience, algorithm, expiration, not-before time, required claims, and authorization rules.

Is JWT authentication the same as OAuth 2.0?

No. OAuth 2.0 is an authorization framework. JWT is a token format. OAuth systems may issue JWT access tokens, opaque access tokens, or other credential formats.

CONTINUE LEARNING

Inspect a token, then explore the formats behind it

Use browser tools with non-sensitive sample data and validate real tokens only inside your trusted application environment.

Suggested tools

Continue with related browser utilities

View sitemap ->