API Security Understanding API Keys Tokens and Credentials

Every time an app on your phone talks to the internet to fetch data — like checking the weather or loading your bank balance — it uses something called an API (Application Programming Interface). Think of an API as a waiter in a restaurant: you place your order, the waiter goes to the kitchen, and brings back your food. But that waiter needs to prove they work there before the kitchen will hand over anything. That proof is what API security is all about.

This page explains how APIs protect themselves using keys, tokens, and credentials — in plain, everyday language.

What Is an API and Why Does It Need Security?

An API lets two software systems talk to each other. When you use a travel booking app, it contacts airline APIs to check seat availability. When you log in with Google, your app contacts Google's API to verify your identity.

Without security, anyone on the internet could send requests to these APIs — stealing data, crashing systems, or pretending to be someone they are not. API security prevents this by checking: Who are you? Are you allowed to do this?

The Restaurant Analogy for API Security

┌─────────────────────────────────────────────────────────┐
│                    RESTAURANT (API)                     │
│                                                         │
│  YOU (App)  ──[Order Slip + Staff ID]──▶  WAITER (API)  │
│                                              │          │
│                                              ▼          │
│                                         KITCHEN         │
│                                    (Server / Database)  │
│                                              │          │
│  YOU (App)  ◀──[Your Food / Data] ───────────┘          │
└─────────────────────────────────────────────────────────┘

Staff ID = API Key / Token / Credentials

No valid ID means no food. No valid API key means no data.

What Is an API Key?

An API key is a long string of letters and numbers — like a password — that identifies who is making a request to an API. It tells the API server: "This request is coming from a trusted application."

A real API key looks something like this:

sk-abc123XYZ456def789GHI000

You never share this publicly. If someone else gets your API key, they can use your account, run up charges in your name, or steal your data.

How an API Key Works — Step by Step

┌────────────────────────────────────────────────────────────────┐
│                    HOW API KEY WORKS                           │
│                                                                │
│  STEP 1: Developer signs up on API provider's website          │
│          Example: OpenWeatherMap, Google Maps, Stripe          │
│                         │                                      │
│                         ▼                                      │
│  STEP 2: Provider generates a unique API Key for you           │
│          Key: "weath_91kLmNoPq2rStuVwX3yZ"                     │
│                         │                                      │
│                         ▼                                      │
│  STEP 3: Developer adds key to every API request               │
│          GET /weather?city=Delhi&apikey=weath_91kLmN...        │
│                         │                                      │
│                         ▼                                      │
│  STEP 4: API server checks the key                             │
│          ✅ Valid Key → Returns weather data                   │
│          ❌ Invalid Key → Returns "401 Unauthorized" error     │
└────────────────────────────────────────────────────────────────┘

Where API Keys Are Used

  • Weather apps (OpenWeatherMap, AccuWeather APIs)
  • Map services (Google Maps API)
  • Payment gateways (Stripe, PayPal APIs)
  • SMS services (Twilio API)
  • AI services (OpenAI, Anthropic APIs)

Limitations of API Keys

API keys are simple but not very smart. They only check who is calling, not what that caller is allowed to do. They also do not expire automatically. If stolen, they stay dangerous until you manually delete them.

What Is an API Token?

A token is a more advanced form of API credential. It does everything an API key does — but it also carries extra information, like an expiry time and a list of permissions. Think of it like a theme park wristband.

API Key vs Token — Theme Park Analogy

┌───────────────────────────────────────────────────────────────┐
│               THEME PARK ACCESS COMPARISON                    │
│                                                               │
│  API KEY                     TOKEN (e.g., JWT)                │
│  ────────────────────        ─────────────────────────────    │
│  🔑 Simple metal key         🎢 Wristband with printed info   │
│                                                               │
│  • Opens specific door       • Name: John Smith               │
│  • Valid forever             • Access: Rides A, B, C only     │
│  • No extra info             • Expires: 5:00 PM today         │
│  • Cannot be restricted      • Cannot enter VIP zone          │
│                                                               │
│  If key is copied →          If wristband is copied →         │
│  anyone can enter            it expires anyway at 5 PM        │
└───────────────────────────────────────────────────────────────┘

Tokens are smarter. They expire, they limit what you can do, and they can be made invalid without deleting your whole account.

Types of Tokens Used in APIs

1. Bearer Tokens

A bearer token is the most common type. Whoever "bears" (carries) the token gets access. You include it in every request inside the HTTP header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

The API server sees this header and knows who you are and what you can access.

2. JWT — JSON Web Token

A JWT (pronounced "jot") is a specific format of bearer token. It looks like three blocks of text joined by dots. Each block contains encoded information.

┌─────────────────────────────────────────────────────────────┐
│                  JWT TOKEN STRUCTURE                        │
│                                                             │
│  eyJhbGci...  .  eyJ1c2Vy...  .  SflKxwRJ...                │
│       │               │               │                     │
│       ▼               ▼               ▼                     │
│   HEADER           PAYLOAD         SIGNATURE                │
│   ────────         ────────        ──────────               │
│   • Token type     • User ID       • Proves the             │
│   • Algorithm      • Expiry time     token was not          │
│     used to        • Permissions     tampered with          │
│     sign it        • Role (admin,                           │
│                      user, guest)                           │
│                                                             │
│  All three parts are Base64-encoded (not encrypted!)        │
│  Anyone can decode the header and payload.                  │
│  Only the signature is secret.                              │
└─────────────────────────────────────────────────────────────┘

Because anyone can read the payload, you should never put passwords or sensitive personal data inside a JWT. The signature just proves nobody tampered with it.

3. Refresh Tokens

Access tokens expire quickly — sometimes in 15 minutes or 1 hour. A refresh token is a longer-lived token that lets your app silently get a new access token without asking the user to log in again.

┌──────────────────────────────────────────────────────────────┐
│              ACCESS TOKEN vs REFRESH TOKEN                   │
│                                                              │
│  ACCESS TOKEN                  REFRESH TOKEN                 │
│  ─────────────────             ──────────────────────────    │
│  🎟 Short-term ticket          🏦 Bank vault key             │
│                                                              │
│  • Lives: 15 min – 1 hour      • Lives: 7–30 days            │
│  • Used: Every API request     • Used: Only to get           │
│  • Sent in every header          a new access token          │
│  • High exposure risk          • Stored securely,            │
│                                  rarely sent over wire       │
│                                                              │
│  Flow:                                                       │
│  App ──▶ API [access token] ──▶ Gets data                    │
│  Access token expires ──▶                                    │
│  App ──▶ Auth server [refresh token] ──▶ New access token    │ 
└──────────────────────────────────────────────────────────────┘
4. OAuth Tokens

OAuth is an authorization system many apps use. When you click "Login with Google" or "Continue with Facebook," OAuth is at work. It gives your app a token to act on your behalf — without ever handing over your Google or Facebook password.

┌──────────────────────────────────────────────────────────────┐
│               OAUTH FLOW — "LOGIN WITH GOOGLE"               │
│                                                              │
│  1. You click "Login with Google" on a travel app            │
│                    │                                         │
│                    ▼                                         │
│  2. Travel app redirects you to Google's login page          │
│                    │                                         │
│                    ▼                                         │
│  3. You enter YOUR Google password (on Google's page)        │
│     Travel app NEVER sees your password                      │
│                    │                                         │
│                    ▼                                         │
│  4. Google asks: "Allow Travel App to see your name          │
│     and email?" → You click Allow                            │
│                    │                                         │
│                    ▼                                         │
│  5. Google sends an OAuth access token to the travel app     │
│                    │                                         │
│                    ▼                                         │
│  6. Travel app uses that token to access your Google info    │
│     Token only allows: name + email                          │
│     Token does NOT allow: read Gmail, delete files, etc.     │
└──────────────────────────────────────────────────────────────┘

What Are API Credentials?

API credentials is the umbrella term that covers all forms of identity proof used to access an API. This includes API keys, tokens, client IDs, client secrets, usernames, and passwords used in API contexts.

Common Credential Types at a Glance

┌───────────────────────────────────────────────────────────────┐
│              API CREDENTIAL TYPES OVERVIEW                    │
│                                                               │
│  TYPE              WHAT IT IS          WHERE USED             │
│  ─────────────── ─ ──────────────────  ──────────────────     │
│  API Key           Static secret ID    Simple data APIs       │
│  Bearer Token      Temporary pass      Most modern APIs       │
│  JWT               Encoded info pack   Auth systems           │
│  OAuth Token       Delegated access    Social logins          │
│  Client ID         App identifier      OAuth setup            │
│  Client Secret     App's password      OAuth backend          │
│  Basic Auth        username:password   Legacy/simple APIs     │
│  Session Cookie    Browser-stored ID   Web app APIs           │
└───────────────────────────────────────────────────────────────┘

Client ID and Client Secret

In OAuth systems, two credentials work as a pair:

  • Client ID — This is public. It identifies your application to the API provider. Think of it as your app's username.
  • Client Secret — This is private. It proves your app is who it claims to be. Think of it as your app's password.
┌──────────────────────────────────────────────────────────────┐
│              CLIENT ID + CLIENT SECRET ANALOGY               │
│                                                              │
│        Like a business bank account:                         │
│                                                              │
│  Client ID     =  Account Number  (shared openly)            │
│  Client Secret =  PIN / Password  (kept strictly private)    │
│                                                              │
│  Anyone can know your account number.                        │
│  Only you should know the PIN.                               │
└──────────────────────────────────────────────────────────────┘

How API Authentication Works in Practice

Authentication is the process of proving your identity. APIs use several methods to do this.

Method 1 — API Key in Query String

The key is added directly to the URL. Simple, but risky because URLs often appear in server logs.

GET https://api.example.com/data?api_key=abc123XYZ

⚠️ Problem: The key appears in browser history and server logs

Method 2 — API Key in HTTP Header

The key goes in the request header, away from the URL. This is safer.

GET https://api.example.com/data
Headers:
  X-API-Key: abc123XYZ
  Content-Type: application/json

✅ Better: Key is not visible in the URL or logs

Method 3 — Bearer Token in Authorization Header

This is the modern standard for secure API authentication.

GET https://api.example.com/profile
Headers:
  Authorization: Bearer eyJhbGciOiJSUzI1NiJ9...

✅ Best: Short-lived, encrypted in transit, standard format

Method 4 — Basic Authentication

The app sends a username and password encoded in Base64. This is older and generally not recommended for APIs because Base64 encoding is easily reversed.

GET https://api.example.com/data
Headers:
  Authorization: Basic dXNlcjpwYXNzd29yZA==
                             │
                             ▼
                    Decoded: "user:password"

⚠️ Risky unless used over HTTPS with strict controls

API Authorization — What Are You Allowed to Do?

Authentication answers "Who are you?" Authorization answers "What are you allowed to do?" These are two separate things, and both matter.

Authentication vs Authorization — The Hotel Analogy

┌──────────────────────────────────────────────────────────────┐
│                    HOTEL SECURITY                            │
│                                                              │
│  AUTHENTICATION                AUTHORIZATION                 │
│  ──────────────────────        ───────────────────────────   │
│  🪪 Showing your ID            🗝 Using your room key        │
│    at check-in                   to open your room           │
│                                                              │
│  • Proves you are a guest      • Limits which rooms          │
│  • Done once at front desk       you can enter               │
│  • Question: "Who are you?"    • Question: "What can         │
│                                  you access?"                │
│                                                              │
│  In API terms:                                               │
│  • Auth: Token proves you      • Authz: Token says you       │
│    are "user_id: 4821"           can only read posts,        │
│                                  not delete them             │
└──────────────────────────────────────────────────────────────┘

API Scopes — Fine-Grained Permission Control

Modern OAuth systems use scopes to define exactly what a token can do. When you log in with Google on a third-party app, you see a list like "This app wants to: read your email, see your contacts." Each item in that list is a scope.

┌──────────────────────────────────────────────────────────────┐
│                  OAUTH SCOPES EXAMPLE                        │
│                                                              │
│  Google API Scopes:                                          │
│                                                              │
│  Scope String                    What It Allows              │
│  ─────────────────────────────── ─────────────────────────   │
│  https://...gmail.readonly       Read emails only            │
│  https://...gmail.send           Send emails                 │
│  https://...drive.readonly       View Google Drive files     │
│  https://...calendar.events      Read/write calendar         │
│  profile                         Basic profile info only     │
│  email                           Email address only          │
│                                                              │
│  A token with scope "profile email" CANNOT read Gmail.       │
│  A token with scope "gmail.readonly" CANNOT send email.      │
└──────────────────────────────────────────────────────────────┘

Scopes follow the Principle of Least Privilege: give the minimum access needed to do the job, nothing more.

How Tokens Are Issued — The Token Lifecycle

Tokens do not last forever. Understanding how they are born, used, and retired is key to understanding API security.

┌──────────────────────────────────────────────────────────────┐
│               TOKEN LIFECYCLE DIAGRAM                        │
│                                                              │
│   APP                AUTH SERVER              API SERVER     │
│   ───                ───────────              ──────────     │
│    │                      │                       │          │
│    │── Login request ────▶│                       │          │
│    │   (credentials)      │                       │          │
│    │                      │                       │          │
│    │◀── Access Token ─────│                       │          │
│    │    + Refresh Token   │                       │          │
│    │                      │                       │          │
│    │── API Request ───────────────────────────────▶│         │
│    │   [Access Token]                              │         │
│    │                                               │         │
│    │◀── Response (data)  ──────────────────────────│         │
│    │                                               │         │
│    │   (Access token expires after 1 hour)         │         │
│    │                                               │         │
│    │── Refresh request ──▶│                        │         │
│    │   [Refresh Token]    │                        │         │
│    │                      │                        │         │
│    │◀── New Access Token ─│                        │         │
│    │                      │                        │         │
│    │── API Request ───────────────────────────────▶│         │
│    │   [New Access Token]                          │         │
└──────────────────────────────────────────────────────────────┘

Common Threats to API Keys and Tokens

Understanding what can go wrong helps you protect your credentials better.

Threat 1 — Exposed API Keys in Code

Developers sometimes accidentally push their API keys into public GitHub repositories. Attackers scan GitHub constantly for exposed keys and use them within minutes.

┌──────────────────────────────────────────────────────────────┐
│            EXPOSED KEY SCENARIO                              │
│                                                              │
│  Developer pushes code to GitHub:                            │
│                                                              │
│  const API_KEY = "sk_live_9xK2mNpQr5sTuVw3yZaB"  ← EXPOSED   │
│                                                              │
│  Timeline:                                                   │
│  0 min  → Code pushed to public repo                         │
│  1 min  → Automated bots scan and find the key               │
│  5 min  → Attacker uses key to make API calls                │
│  1 hour → Developer gets a massive bill or data breach       │
│                                                              │
│  Solution: Use environment variables, never hardcode keys.   │
│  Use: process.env.API_KEY  (not the actual key in code)      │
└──────────────────────────────────────────────────────────────┘

Threat 2 — Token Theft via Man-in-the-Middle Attack

If an API is accessed over plain HTTP (not HTTPS), an attacker sitting on the same network can intercept the request and steal the token. This is why all API communication must use HTTPS.

┌──────────────────────────────────────────────────────────────┐
│           MAN-IN-THE-MIDDLE ATTACK                           │
│                                                              │
│  WITHOUT HTTPS:                                              │
│                                                              │
│  Your App ──▶ [Token visible in plain text] ──▶ Attacker     │
│                                            ──▶ API Server    │
│                                                              │
│  Attacker captures token and reuses it.                      │
│                                                              │
│  WITH HTTPS:                                                 │
│                                                              │
│  Your App ──▶ [Token encrypted in transit] ──▶ API Server    │
│                                                              │
│  Attacker sees only scrambled, useless data.                 │
└──────────────────────────────────────────────────────────────┘

Threat 3 — Token Replay Attack

An attacker captures a valid token and replays it later to make unauthorized requests. Short expiry times on access tokens limit the damage window significantly.

Threat 4 — Brute Force on API Keys

Attackers try thousands of key combinations hoping one works. APIs defend against this using rate limiting — blocking IPs that make too many failed requests in a short time.

┌──────────────────────────────────────────────────────────────┐
│                RATE LIMITING DEFENSE                         │
│                                                              │
│  Request 1:  API Key = "aaa111" → ❌ Invalid                 │    
│  Request 2:  API Key = "aaa112" → ❌ Invalid                 │ 
│  Request 3:  API Key = "aaa113" → ❌ Invalid                 │ 
│  ...                                                         │
│  Request 100: ──▶ 429 Too Many Requests                      │
│               ──▶ IP blocked for 15 minutes                  │
│                                                              │
│  Attacker slowed down significantly.                         │
└──────────────────────────────────────────────────────────────┘

Best Practices for Storing and Using API Keys and Tokens

Do This

  • Store keys in environment variables — Never write them directly in your source code.
  • Use HTTPS everywhere — Never send tokens over plain HTTP.
  • Set token expiry times — Short-lived access tokens reduce damage if stolen.
  • Use scopes — Request only the permissions your app actually needs.
  • Rotate keys regularly — Replace old API keys with new ones periodically.
  • Revoke immediately on suspicion — If you think a key is compromised, delete it right away.
  • Log API usage — Monitor for unusual patterns that might signal a stolen key in use.

Never Do This

  • Never paste an API key into a chat message, forum post, or email.
  • Never commit an API key to version control (Git, GitHub, GitLab).
  • Never store tokens in plain text files.
  • Never share a production API key with developers who only need a test key.
  • Never ignore API usage alerts from your provider.

Environment Variables — The Safe Way to Store Keys

┌──────────────────────────────────────────────────────────────┐
│           ENVIRONMENT VARIABLE APPROACH                      │
│                                                              │
│  WRONG — Key hardcoded in code:                              │
│  ─────────────────────────────                               │
│  api_key = "sk_live_9xK2mNpQr5"    ← Anyone can read this    │
│                                                              │
│  RIGHT — Key stored as environment variable:                 │
│  ────────────────────────────────────────────                │
│  In your .env file (never committed to Git):                 │
│  API_KEY=sk_live_9xK2mNpQr5                                  │
│                                                              │
│  In your code:                                               │
│  api_key = os.environ.get("API_KEY")   ← Safe reference      │
│                                                              │
│  Code shows no actual key → Safe to share publicly           │
└──────────────────────────────────────────────────────────────┘

API Key vs Token — Side-by-Side Comparison

┌───────────────────────────────────────────────────────────────┐
│           API KEY vs TOKEN — FULL COMPARISON                  │
│                                                               │
│  FEATURE              API KEY         TOKEN (JWT/OAuth)       │
│  ─────────────────    ───────────     ─────────────────────   │
│  Expiry               ❌ No           ✅ Yes (configurable)  │
│  Carries user info    ❌ No           ✅ Yes                 │
│  Permission scopes    ❌ Limited      ✅ Fine-grained        │
│  Can be revoked       ✅ Yes          ✅ Yes                 │
│  Auto-refreshable     ❌ No           ✅ Yes (refresh token) │
│  Complexity           🟢 Simple       🟡 Moderate            │
│  Best for             Server-to-server  User-facing apps      │
│                       integrations                            │
│  Risk if stolen       High (no expiry)  Lower (expires soon)  │
└───────────────────────────────────────────────────────────────┘

Real-World Examples to Connect the Concepts

Example 1 — Weather App

A weather app on your phone uses an API key to contact OpenWeatherMap's servers. The key identifies the app to the weather service. The app developer pays for this access, so the key ensures only their app can make requests on their account.

Example 2 — Online Shopping Login

When you click "Login with Google" on an online shopping site, OAuth tokens are used. Google issues an access token to the shopping site. That token tells the site your name and email address — and nothing else. The shopping site never gets your Google password.

Example 3 — Mobile Banking App

Your bank's mobile app logs you in and receives a short-lived JWT access token (valid for 15 minutes) and a longer-lived refresh token (valid for 30 days). Every time the access token expires, the app quietly uses the refresh token to get a new one — so you stay logged in without entering your password again.

Example 4 — Business Sending Email

A company uses SendGrid's email API to send order confirmations to customers. Their application stores an API key as an environment variable on their server. The key is never visible in the code, never in GitHub, and gets rotated every 90 days as a security rule.

Summary: Key Points to Remember

  • An API key is a static identifier that tells an API server which application or developer is making the request. It does not expire on its own and must be guarded carefully.
  • A token is a smarter credential that carries expiry times, permissions, and user information. JWT is a widely used token format. OAuth tokens enable delegated access without sharing passwords.
  • Refresh tokens silently renew expired access tokens so users stay logged in without re-entering passwords.
  • Scopes limit what a token can do, following the Principle of Least Privilege.
  • Authentication proves identity; authorization defines what that identity is allowed to do.
  • Always use HTTPS, store keys in environment variables, set short token expiry times, and rotate credentials regularly.
  • An exposed API key is a serious security incident. Revoke it immediately and investigate how it was used.

Leave a Comment