Protect an API
This guide protects your API with Goiabada, so it answers only callers holding the right permission, whether an app calls it for a user or a service calls it on its own.
Callers show what they may do with an access token: a signed JWT the auth server issues, which carries the permission scopes its holder was granted. Your API checks the token on every request, on its own, with the auth server’s public keys. It never has to call the auth server to do that.
Let users call your API
Section titled “Let users call your API”-
Describe your API. In the admin console, open Admin, Resources and permissions and click New resource. Enter a Resource identifier, such as
product-api, and a Description, and click Create resource. -
Click its identifier and open Permissions. For each thing your API lets callers do, enter a Permission identifier, such as
readorwrite, and click Add permission. Click Save when the list is done. Each one is a scope your app can ask for,product-api:readandproduct-api:write. See Resources and permissions. -
Give the permissions to the users who need them, on each user’s Permissions tab, or to a group, on the group’s Permissions tab, so every member gets them. Choose the Resource and the Permission, click Grant permission, and click Save: until you save, nothing is granted.
-
Have your app ask for the scope when it signs the user in, beside the OpenID Connect scopes it already asks for, as in Add sign-in to a web app:
GET /auth/authorize?client_id=my-web-app&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&response_type=code&scope=openid%20email%20product-api%3Aread&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&state=af0ifjsldkj&nonce=n-0S6_WzA2Mj HTTP/1.1Host: auth.example.com -
Your app sends the access token it gets to your API, in the
Authorizationheader:Terminal window curl https://api.example.com/products \-H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Ii4uLiJ9..." -
Your API checks the token before it answers, as Tokens describes: its signature against the keys at
https://auth.example.com/certs,at+jwtas thetypin its header, anissequal to the auth server’s issuer, anexpthat hasn’t passed,product-apiamong itsaud, and the permission the operation needs in itsscope. If your JWT library accepts onlytyp: JWTby default, allowat+jwt, or it refuses every token.
A token that fails a check gets 401 Unauthorized, and one that’s valid but lacks the permission gets 403 Forbidden, as RFC 6750 section 3.1 describes for an API answering bearer tokens.
Let a service call your API
Section titled “Let a service call your API”A service that calls your API on its own, with no user, such as a nightly job, gets its own token with the client credentials flow.
-
Register the service. In the admin console, open Admin, Clients and click New client. Enter a Client identifier, such as
billing-service, turn on Client credentials, turn off Authorization code with PKCE, and click Create client. -
Click its identifier. On Permissions, choose the Resource and the Permission the service needs, click Grant permission, and click Save. On Authentication, click Show and copy the Client secret to the service’s configuration.
-
From the service, ask the token endpoint for a token:
Terminal window curl -X POST https://auth.example.com/auth/token \-u billing-service:CLIENT_SECRET \-d grant_type=client_credentials \-d scope=product-api:read -
Read the access token from the answer:
{"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ii4uLiJ9...","token_type": "Bearer","expires_in": 300,"scope": "product-api:read"} -
Call your API with it, as step 5 above does. When it expires, ask for a new one: there’s no refresh token.
What a user’s token carries
Section titled “What a user’s token carries”An access token from a sign-in names the user in sub, and carries in scope the permission scopes your app asked for that the user holds, directly or through a group. A permission the user doesn’t hold is left out without an error, so check scope rather than assuming your app got what it asked for. Its aud names the resource of each permission scope, and authserver too when the token carries an OpenID Connect scope or offline_access. Tokens lists every claim.
What a service’s token carries
Section titled “What a service’s token carries”A token from the client credentials flow names no user. Decoded, the one from the steps above looks like this:
{ "iss": "https://auth.example.com", "sub": "billing-service", "aud": "product-api", "client_id": "billing-service", "scope": "product-api:read", "typ": "Bearer", "iat": 1760000000, "nbf": 1760000000, "exp": 1760000300, "jti": "9a6f1c1e-2d0b-4f3e-8a55-0c1b7a3e2f44"}sub and client_id are both the client identifier, and there’s no auth_time, acr, amr or sid, since nobody signed in. Its header’s typ is at+jwt too, and your API checks it exactly as it checks a user’s token.
The scope is the client’s own permissions, never a user’s. Leave scope out of the request to get every permission the client holds, as long as it holds one. A scope the client doesn’t hold is refused with invalid_scope, and so is an OpenID Connect scope such as openid, since there’s no user for it to describe. Token lists every refusal.
Only a confidential client can use the flow, since its client secret is all it proves itself with. Keep the secret in the service’s secret store or environment, never in code, and give each service a client of its own, so you can replace one’s secret without touching the others.
The keys
Section titled “The keys”Fetch the key set from /certs once and cache it, then pick the key whose kid matches the one in the token’s header. When a token names a kid your cache doesn’t have, fetch the set again: the auth server publishes the next signing key before it signs anything with it, so a fresh copy has it. See the key set.
What your API can’t see
Section titled “What your API can’t see”An API that checks only the signature trusts a valid token until it expires, even after the user’s session ends or the user is disabled. That’s why access tokens are short, 5 minutes in a new install.
Ask the auth server about a token
Section titled “Ask the auth server about a token”When an operation must stop the moment a token is cut off, have your API also introspect the token: ask the auth server whether it’s still active. Access tokens already issued lists what cuts a token off.
-
Give your API a confidential client of its own: open Admin, Clients, click New client, enter a Client identifier, such as
product-api-introspector, turn off Authorization code with PKCE, and click Create client. On Authentication, click Show and copy the Client secret to your API’s configuration. -
On the client’s Introspection tab, choose
product-api, click Add resource, and click Save. The client can now introspect the tokens whoseaudnamesproduct-api, and no others. -
On each request that needs it, send the token to the introspection endpoint with the client’s credentials:
Terminal window curl -X POST https://auth.example.com/auth/introspect \-u product-api-introspector:CLIENT_SECRET \-d token=eyJhbGciOiJSUzI1NiIsImtpZCI6Ii4uLiJ9... -
Answer the request only when the answer’s
activeistrue, and still check itsscopefor the permission the operation needs.
Each check is a call to the auth server, so keep it for the operations that need it. See Introspect for the answer’s members and errors.
Accept DPoP-bound tokens
Section titled “Accept DPoP-bound tokens”An app using DPoP gets access tokens bound to a key it holds, so a token copied away from it is useless without that key. It calls your API with the DPoP scheme, and a proof, a short JWT signed by the key, in a DPoP header:
GET /products HTTP/1.1Host: api.example.comAuthorization: DPoP eyJhbGciOiJSUzI1NiIsImtpZCI6Ii4uLiJ9...DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...A bound token carries the key’s thumbprint in cnf.jkt. That claim is what says it’s bound: its typ claim is Bearer whether it’s bound or not.
-
Read the
Authorizationheader’s scheme. WithBearer, check the token as step 6 above does, and refuse it with401invalid_tokenif it carriescnf.jkt: a bound token sent as a bearer token is how a copied one would arrive. -
With
DPoP, take the request’s oneDPoPheader, and refuse the request with401invalid_dpop_proofif there’s none, or more than one, or its proof fails any of these checks:Part Check Header typdpop+jwtHeader algOne of the asymmetric algorithms you accept, such as ES256. Nevernoneor a symmetric one such asHS256Header jwkA public key, with no private part. The signature verifies with it htmYour request’s method, exactly, such as GEThtuYour API’s own public URL for the request, such as https://api.example.com/products, without query or fragment. Compare it with the URL your callers use, configured in your API, never one rebuilt from theHostheaderiatWithin a minute of your API’s clock, either side athThe access token’s SHA-256 hash, base64url-encoded without padding jtiNot seen before on this URL: keep each one until its iatfalls out of your window, and refuse it a second time -
Check the token as step 6 above does, and refuse it with
401invalid_tokenif it has nocnf.jkt, or if itscnf.jktisn’t the proof key’s thumbprint: the key’s RFC 7638 thumbprint, with SHA-256, base64url-encoded without padding. Most JWT libraries compute it. -
When your API introspects the token, the answer says the same:
token_typeDPoPand the thumbprint incnf.jktfor a bound token,token_typeBearerand nocnffor an unbound one. Apply steps 1 and 3 to that answer.
Every 401 your API answers names both schemes in WWW-Authenticate, Bearer first, with the error in the challenge of the scheme the request used, and the algorithms it accepts in algs:
HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer realm="product-api", DPoP realm="product-api", algs="ES256 PS256", error="invalid_dpop_proof", error_description="The DPoP proof is invalid."A 403 for a missing permission carries insufficient_scope in the challenge of the scheme used, just the same.
When something goes wrong
Section titled “When something goes wrong”- The app gets
error=invalid_scope, or a token without the permission: see invalid_scope. - The service gets
unauthorized_client: Client credentials is off for its client, or the client is public. - The service gets
invalid_client: the client identifier or secret is wrong, or the client is disabled.