Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

API keys, tokens and rate limits

After this lesson: I can protect an API with keys, tokens and limits.

55 min lesson4 commandsPostgreSQL and PostgREST lab: a database and a REST API in the browser

Anyone can call an open API

API security is the set of checks that make sure only the right callers use an API, only as much as they should. Without it, anyone who finds the address can read your data, change it or run up your bill.

You will learn how a service knows who is calling, what a caller may do, and how it stops one caller using too much.

By the end of this lesson

Note

I can protect an API with keys, tokens and limits.

Key words

WordWhat it means
Authenticationproving who the caller is
Authorisationdeciding what that caller may do
API keya long secret string that names one caller
Bearer tokena short-lived secret sent in a header
Expirythe time after which a token stops working
Rate limita cap on how many requests a caller may make

The cells students fill in are left blank in this preview.

Your own lab only

Warning

Look at your lab and at the ideas in this lesson. Never try to get past the keys of a service that is not yours. That is a crime under the Computer Misuse Act 1990, even if you only meant to look.

Authentication asks who, authorisation asks what

Authentication answers: who are you? A key or a token proves it. Authorisation answers: what may you do? A reader may list books and only an admin may delete them.

They give different codes. Not proved gives 401. Proved, but not allowed, gives 403.

Worked example: 401 or 403

SituationWho is the caller?Allowed?Code
No key sentUnknownNot asked401
A key that does not existUnknownNot asked401
Ana's key, listing booksAnaYes200
Ana's key, deleting a bookAnaNo, she is a reader403

The cells students fill in are left blank in this preview.

Look at an API that asks for nothing

Run the next two commands to make a books table. Then ask the API for the books with no key and no token. This lab's API is open to your own private network on purpose, so it answers.

A real service on the internet would answer 401 here.

Give psql the password

Command
export PGPASSWORD=shop

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Make the books table

Command
psql -h db -U shop -c "drop table if exists books; create table books (id serial primary key, title text not null, year int not null, available boolean not null default true); insert into books (title, year, available) values ('Maps of the Sea', 1998, true), ('Rivers of Europe', 2004, false), ('Night Trains', 2011, true); notify pgrst, 'reload schema'"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Ask with no key at all

Command
curl -s -o /dev/null -w "%{http_code}\n" "http://api:3000/books"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Send secrets in a header, never the address

A caller sends its secret in the Authorization header. A bearer token is sent as Authorization: Bearer and then the token. An API key is often sent in a header of its own.

Never put a secret in the address. Addresses are written to logs, browser history and shared links. Use HTTPS (HTTP with encryption) so nobody on the way can read the header.

A request that carries a token (an example)

Code: bash
GET /books HTTP/1.1
Host: library.example
Authorization: Bearer 7f3a9c1e5b8d

# This is the lesson's own example. The token is made up.
# The server looks the token up, finds the caller and checks the expiry.

Worked example: key and token compared

PropertyAPI keyBearer token
LifetimeLong, until someone revokes itShort, often 15 to 60 minutes
NamesOne application or personOne user session
If it leaksRevoke it and issue anotherIt stops working at its expiry
Stored by the serverAs a hash, not as plain textAs a signed value or a lookup

The cells students fill in are left blank in this preview.

Hash a made-up key

Command
printf 'key-3f9a' | sha256sum

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A common mistake

Warning

Many people think a key hidden inside a phone app or a web page is safe. It is not. Anyone can read what an app sends. Keep secrets on a server you control, give each caller a key of its own, and revoke a key that leaks.

A rate limit stops one caller using everything

A rate limit caps how many requests a caller may make in a time. It protects the service from bugs, from one greedy client and from guessing attacks.

A common design is a token bucket. The bucket holds a few tokens and gains one every second up to a maximum. Each request spends one. With none left, the answer is 429.

Worked example: a bucket of three

Time (seconds)Tokens beforeRequestTokens after
03Allowed2
02Allowed1
01Allowed0
00Refused with 4290
22Allowed1

The cells students fill in are left blank in this preview.

About this lab and its source: PostgreSQL and PostgREST lab: a database and a REST API in the browser

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.