Performance & Security

API Security Basics: Keys, Tokens and Rate Limits

APIs connect your website, apps and partners to your data. Here are the security basics every API should have, explained without the jargon.

Quick answer: Good API security starts with a few essentials: serve every request over HTTPS, require authentication (API keys for simple server to server use, OAuth 2.0 and tokens for anything acting on behalf of a user), check permissions on every request, validate all input, limit how many requests each client can make, and log activity so you can spot abuse. None of these are exotic. Most API breaches happen because one of the basics was skipped.

APIs now sit behind a great deal of everyday business software. Your mobile app talks to your server through an API. Your website sends orders to your fulfilment system through an API. Partners pull stock levels or prices from an API you expose. Every one of those connections is a door into your data, and doors need locks.

This guide covers the core controls in plain language. It is written for business owners and managers who commission or run APIs, as well as developers who want a checklist.

Why APIs are attractive targets

A website page shows data to a person. An API hands data to a program, usually in a structured format such as JSON, and often in bulk. That makes APIs efficient for legitimate use and equally efficient for attackers. A single weakness, such as an endpoint that returns any customer’s record if you change the ID in the URL, can expose an entire database to a simple script.

APIs are also easy to forget. A web page that breaks gets noticed quickly. An old API endpoint that nobody uses any more can sit quietly for years, unpatched and unmonitored.

1. Encrypt everything with HTTPS

Every API request and response should travel over HTTPS (TLS). Without it, anyone on the network path, for example on public Wi-Fi, can read API keys, tokens and data in transit, or tamper with them.

  • Use HTTPS for every endpoint, not just login.
  • Redirect or reject plain HTTP requests.
  • Disable old protocols such as SSLv3 and weak cipher suites.
  • Keep certificates valid and renewed. Let’s Encrypt, now in public beta, provides free certificates. See our guide to Let’s Encrypt.

2. Authenticate every client

Authentication answers “who is calling?” There are several common approaches, each suited to different situations.

API keys

An API key is a long random string issued to a client, sent with each request, usually in a header. Keys are simple and work well for server to server integrations where a single trusted system calls your API.

Good practice with keys:

  • Send them in a request header, not in the URL, because URLs end up in logs and browser history.
  • Issue a separate key for each client so you can revoke one without affecting others.
  • Allow keys to be rotated easily.
  • Never put a secret key in a mobile app or JavaScript that runs in the browser. Anyone can extract it.

OAuth 2.0

When an application needs to act on behalf of a user, for example a third party app reading a customer’s orders, OAuth 2.0 is the standard approach. The user signs in with you and approves access, and the app receives an access token rather than the user’s password. Tokens can be limited in scope (for example “read orders” but not “change account details”) and can expire.

OAuth 2.0 has several flows. For web applications with a server, the authorisation code flow is the usual choice. It is easy to get details wrong, so use a well maintained library rather than writing it from scratch.

JSON Web Tokens (JWT)

JWT, standardised in 2015 as RFC 7519, is a compact format for tokens that carry claims, such as a user ID and an expiry time, signed so the server can check they have not been altered. JWTs are popular for single page applications and mobile apps because the server can verify them without a database lookup.

Points to watch:

  • Always verify the signature, and reject tokens that use the “none” algorithm.
  • Keep expiry times short and use refresh tokens for longer sessions.
  • Do not store sensitive data inside the token. It is signed, not encrypted, so anyone can read the contents.

HMAC request signing

For high value integrations, the client can sign each request with a shared secret using HMAC. The server recalculates the signature and rejects any request that does not match. Including a timestamp in the signature also blocks replay attacks, where someone resends a captured request.

3. Authorise every request

Authentication tells you who is calling. Authorisation decides what they are allowed to do. Many serious API flaws are authorisation failures:

  • A logged in user can view another user’s invoice by changing the ID in /invoices/1234.
  • A normal account can call an admin endpoint because the check only happens in the user interface.

Check permissions on the server for every request, for every object returned. Do not rely on the app or website to hide buttons. OWASP lists insecure direct object references and missing function level access control in its Top 10, and both apply strongly to APIs.

4. Validate input and limit output

Treat everything a client sends as untrusted.

  • Validate types, lengths and formats against a defined schema.
  • Use parameterised queries to prevent SQL injection.
  • Reject unexpected fields rather than silently saving them.
  • Return only the fields the client needs. Do not send whole database rows and rely on the client to ignore the rest.
  • Avoid detailed error messages that reveal stack traces, database names or server versions.

A clear API design helps here. Our article on REST API design covers consistent resources, status codes and error formats.

5. Rate limit and throttle

Rate limiting caps how many requests a client can make in a period, for example a set number per minute per API key. It protects you from:

  • Brute force attacks on login or token endpoints
  • Scraping of your data in bulk
  • Accidental overload from a buggy client stuck in a loop
  • Some denial of service attempts

Return a 429 Too Many Requests status when a client exceeds the limit, and include headers telling clients their remaining allowance. Apply stricter limits to sensitive endpoints such as login and password reset.

An API gateway can handle rate limiting, authentication and logging in one place in front of your services. See our guide to API gateways for when that makes sense.

6. Log, monitor and alert

You cannot respond to what you cannot see. Log each request with the client identity, endpoint, time, response status and source IP address. Then watch for patterns:

  • Spikes in failed authentication
  • A single client requesting unusual volumes of data
  • Requests to endpoints that should no longer be in use
  • Errors that suggest someone is probing for weaknesses

Do not log full passwords, tokens or card numbers. Keep logs somewhere an attacker on the API server cannot easily erase them.

7. Manage the API’s lifecycle

  • Keep an inventory. Know every API and endpoint you run, including old versions.
  • Retire old versions. Give clients notice, then switch them off.
  • Patch dependencies. Frameworks and libraries behind the API need updates like any software.
  • Test security. Include API endpoints in penetration tests and code reviews.
  • Document properly. Clear documentation, for example with an OpenAPI (Swagger) definition, helps developers use the API correctly and helps reviewers see what is exposed.

A quick checklist

  • HTTPS on every endpoint
  • Authentication on every endpoint that is not deliberately public
  • Separate, revocable credentials per client
  • No secrets in mobile apps or browser code
  • Server side permission checks on every object
  • Input validation and parameterised queries
  • Minimal data in responses and safe error messages
  • Rate limits, with tighter limits on login endpoints
  • Request logging and alerts
  • An up to date inventory of APIs and versions

FAQ

Are API keys secure enough?

For server to server integrations over HTTPS, with keys kept secret and rotated, they are often fine. For user facing apps, use OAuth 2.0 and tokens instead.

Should a public API still have authentication?

Usually yes, even if keys are free. Keys let you rate limit, monitor usage and block abusive clients.

Is JWT better than session cookies?

Neither is universally better. JWTs suit APIs called by apps and other services. Traditional sessions remain fine for many server rendered websites.

How often should we review API security?

Whenever you add endpoints or integrations, and as part of a regular security review at least once a year.

Build security in from the start

Adding security after an API is live is always harder than designing it in. If you are planning a new integration or want a second look at an existing API, see how we help businesses turn visitors into customers with fast, secure sites and systems.

About the author

Imran M

Leave a Reply

Your email address will not be published. Required fields are marked *

Ready to improve your website?

Let's build a faster, higher performing website.