Using access tokens
Getting an access tokenA token that a client presents to an API to use access it has been granted, usually limited in what it allows and how long it lasts. It authorizes API calls; it does not tell the client who signed in. took a trip through Ava's browser and a direct exchange at the token endpointThe authorization server address where clients exchange an authorization code, refresh token, or other grant for tokens, in a direct request rather than through a browser redirect.. Using it looks like the easy part, one header on an ordinary HTTPSHTTP protected by TLS, so traffic is encrypted and checked for changes while it travels. It protects the connection, but does not prove that the site at the other end is honest. request, but the client still decides where the tokenA piece of data issued by a trusted service that a client presents as a credential, for example to call an API or to report a sign-in. Some tokens carry readable claims; others are random strings that only the issuer can interpret. goes, what it assumes about it, and what to do when the APIAn application programming interface: a defined way for software to interact with a service. A web API offers endpoints where other programs send HTTP requests. says no. This lesson follows the printer as it uses its token to read Ava's photos.
Presenting a token
Ava is choosing pictures for her photo book at the printer, and she opens album 42. To show her its photos, the printer's backend has to ask the photo API for them, and it holds the credential to do that: the access token from the code exchange, good for ten minutes and for photos.read.
The token response said token_type was Bearer. A bearer tokenA token that works for whoever presents it: the API checks that the token is genuine and current, not who is holding it. That is why bearer tokens must be kept from being copied. works for whoever holds it, the way cash does: the API asks for nothing beyond the token itself. The printer sends it in the Authorization header, after the word Bearer. All domains and tokens in these examples are fictional.
GET /albums/42/photos HTTP/1.1
Host: api.photos.example
Authorization: Bearer demo-access-token-7This is the standard place for a bearer token, and every API that accepts bearer tokens must support it. Above all, it keeps the token out of the address. The scheme name Bearer is not case-sensitive, so bearer works too; the token after it is sent exactly as it was issued.
The bearer token standard describes two other ways to send a token. One puts it in the query string:
GET /albums/42/photos?access_token=demo-access-token-7 HTTP/1.1
Host: api.photos.exampleNow the token is part of the address, and addresses travel. Servers and proxies write full URLs to their logs, browsers keep them in history, caches store responses under them, and depending on the referrer policy, a page can pass its address to other sites in the Referer header. Each is a copy of the token where nobody treats it as secret, and current security guidance says clients must not send access tokens this way.
The other method sends access_token as a field in a form-encoded request body. It can't be used with GET, which has no body, and the standard says it should not be used unless the client cannot set the Authorization header, a limitation of some old browser environments that the printer's backend does not share. An API may refuse both alternatives, and a request that sends the token in more than one way at once is malformed.
Treating the token as opaque
To the printer, demo-access-token-7 is a string to store and send, even when the photo service issues tokens that can be decoded. As Inside a JWT showed, a JWTA JSON Web Token: a compact token made of Base64url-encoded parts that carries claims and is usually signed. Anyone holding it can decode and read the claims, so the signature shows who issued it but hides nothing. access token decodes to readable claims, such as the account, the scope and the expiry time, and it is tempting to use them.
But the format of an access token is an agreement between the authorization serverIn OAuth, the service that handles a person's sign-in and approval and decides which tokens to issue to a client. It may belong to the same company as the API, but its job is separate. and the API, not with the client. The photo service can switch from JWTs to random reference strings, encryptTransforming data so that only someone holding the right key can read it. It protects confidentiality and, unlike hashing, is designed to be reversed by the key holder. its tokens, or rename a claim, and only its API needs to know. A client that reads the token breaks without warning on the day that happens, which is why the standard profile for JWT access tokens says clients must not inspect the token's content.
Everything the printer needs comes from the token response instead. scope says what was granted, and expires_in says how many seconds the token lasts. Learning which person signed in is a different question, and OpenID ConnectAn identity layer on top of OAuth 2.0 that lets an application sign people in with an account at another service. It adds the ID token, standard claims, and discovery to the OAuth exchange. answers it with the ID tokenIn OpenID Connect, a signed JWT from the provider, addressed to one client, saying which account authenticated, when, and in answer to which request. It reports a sign-in and is not used to call APIs., which is addressed to the client and meant to be read.
The printer turns expires_in into a time as soon as the response arrives. Received at 09:00:00 with expires_in set to 600, the token expires at about 09:10:00 by the printer's own clock. The printer plans to replace it a little early, say at 09:09, so a request started just before expiry does not arrive just after it.
Early replacement is an optimization, not a guarantee. A token can stop working sooner, for example if Ava disconnects the printer at the photo service, so the printer still handles a rejected token on every request.
Reading the API's answer
When the photo API refuses a request for lack of a usable token, it explains in a WWW-Authenticate response header: the scheme, Bearer, followed by attributes. realm names the protected area and is informational. error is the part the client acts on.
If the printer sends no token at all, perhaps because a bug dropped the header, the answer is a bare challenge:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api.photos.example"There is no error code because there was nothing to evaluate, and the bearer token standard says an API should not add error details when a request carried no credentials. An API that reads tokens only from the header gives the same answer to a token in the query string: to it, that request carried no token either.
When a token was sent and rejected, the error code says what kind of problem it was. This header is wrapped here for display:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api.photos.example",
error="invalid_token",
error_description="The access token expired"error_description is a note for developers. Like other optional error text, it is untrusted input, not a message to show Ava. The codes themselves lead to different next steps:
| Response | What it means | What the printer does |
|---|---|---|
| 401 with no error code | No usable credentials were found in the request. | Check that the request really carried the token, in the header. |
400 invalid_request | The request is malformed, for example a token sent two ways at once. | Fix the bug. Sending the same request again will not help. |
401 invalid_token | The token is expired, revoked, malformed, or otherwise not accepted. | Obtain a new access token and retry once. If the new one is rejected too, stop and mark the connection as needing attention. |
403 insufficient_scope | The token is valid but does not cover this operation. | Do not retry with the same token. Ask for more access only if the feature truly needs it. |
Retrying only once is deliberate. A token rejected for a reason other than age, such as a misconfigured API, will fail again however many new tokens the client fetches.
Suppose the printer adds a feature that saves Ava's finished book as a new album in her photo library. Its token has only photos.read, so the API answers:
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer realm="api.photos.example",
error="insufficient_scope",
scope="photos.write"The scope attribute names what the operation needs, for the program rather than for display. A fresh token for the same grant would fail in the same way, and a refresh token cannot add scope. Getting photos.write means sending Ava through authorizationDeciding whether a requested action is permitted, such as whether a signed-in account may delete a particular photo. Authentication says which account is asking; authorization decides what it can do. again, where she can refuse.
Keeping the token where it belongs
Since anyone holding the token can use it, the printer is careful about where it sends one. The rule is short: only to the API the token was issued for, at the address the printer was configured with, over HTTPS with the server's certificate checked.
The easiest way to break that rule is to follow something a response suggests. A page of results might end with a link to the next page:
{
"photos": [ ... ],
"next": "https://api.photos.example/albums/42/photos?page=2"
}Following this link with the token is fine, because it points to the same API. The printer checks that before adding the header: the link's scheme, host and port must equal those of its configured API exactly. A check that the link merely begins with https://api.photos.example would also accept https://api.photos.example.attacker.example/, a different host entirely.
Redirects need the same care. Many HTTP libraries drop the Authorization header when a redirect leads to another host, but not all of them do. For calls that carry tokens, the printer either does not follow redirects automatically or checks each destination first. Addresses from anywhere else, such as a URL in a photo's description, never receive the token at all.
Address the printer is offered
- Next page link
- api.photos.example, same scheme and port
- Look-alike link
- api.photos.example.attacker.example
- Redirect
- Location on another host
- Photo description
- A URL from someone else
Same scheme, host and port as the configured API
- Send the token
- Withhold: a different host entirely
- Withhold unless the destination is checked first
- Never receives the token
A check that the link merely begins with https://api.photos.example would also accept the look-alike host.
Last, the printer keeps the token out of its own records. Request logs that capture headers, error reports that attach the failing request, and analytics that record full URLs are common ways for a token to leak from a well-meaning client. A log line saying that a call failed with invalid_token tells a developer what they need without the token itself.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Present an access token correctly and read every refusalGet a real token for Ava as lab-printer, send it to the sample photo API the right way and three wrong ways, and read each answer the API gives.