Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,212 of 9,212 pages
About the help in other languages
All help pages

Authentication: anonymous requests, keys, tokens and sessions

What this is. How a request to the GraphQL API says who it is, what each kind of credential may do, how keys are made, limited, rotated and revoked, which roles and policies a user needs, and how to keep it all safe.

Download as PDF

Address: https://doc.exponential.earth/learninminutes/exphelp/viewer/headless/authentication.md

On this page

Authentication: anonymous requests, keys, tokens and sessions

What this is. How a request to the GraphQL API says who it is, what each kind of credential may do, how keys are made, limited, rotated and revoked, which roles and policies a user needs, and how to keep it all safe.

When to use it. Before you give a client access; when you choose between anonymous access, a public read key, a server key and OAuth; when a request answers 401, 403 or FORBIDDEN; when you plan key rotation.

Quick example: the same query anonymously and with a personal API key.

EXP=https://www.example.com
# anonymous: runs as the anonymous user of the siteaccess
curl -s "$EXP/api/graphql" -H 'Content-Type: application/json' -d '{"query":"{ currentUser { name anonymous signedInBy } }"}'
# {"data":{"currentUser":{"name":"Anonymous User","anonymous":true,"signedInBy":"anonymous"}}, ...}

# a key: runs as the key's owner
curl -s "$EXP/api/graphql" -H 'Content-Type: application/json' -H "Authorization: Bearer $EXPONENTIAL_API_KEY" \
  -d '{"query":"{ currentUser { login anonymous signedInBy } }"}'
# {"data":{"currentUser":{"login":"frontend","anonymous":false,"signedInBy":"apikey"}}, ...}

Contents

  1. The model: every request is a user
  2. Which credential for which client
  3. Anonymous access
  4. Personal API keys
  5. Scopes
  6. Keys limited to siteaccesses
  7. Public read keys
  8. Creating keys
  9. Rotating keys
  10. Revoking keys and incident response
  11. OAuth tokens
  12. The session of the administration
  13. Roles and policies you need
  14. What happens when a credential is refused
  15. Security guidance
  16. Settings

The model: every request is a user

The API has no permission system of its own. Every request runs as one user of the installation, and that user's roles, policies and limitations decide what it reads and changes, exactly as in the web interface. A credential only says which user and, for keys, which part of the user's rights (the scopes).

currentUser { signedInBy }How the request signed inHeader
anonymousnothingnone
apikeya personal API keyAuthorization: Bearer expk_<12>_<40>
tokenan OAuth access token of the REST layerAuthorization: Bearer <token> (or OAuth <token>)
sessionthe browser session of the administrationthe session cookie (playground, /graphql/query)
console./console exp:graphql:query --as=<login>none

Credentials are read only from the Authorization header. A key sent as api_key, access_token or oauth_token in the query string or the body is refused without being looked up (it would end up in access logs); the refusal is recorded with the reason transport.

Which credential for which client

ClientCredentialScopeWhy
Public pages rendered in the browser, few requestsnone (anonymous)the role Anonymous already decides what visitors may read
A browser front end with heavy traffic that wants its own budgeta public read keygraphql:read, limited to the front end's siteaccessits own rate limit and audit trail; safe to ship because it can only read what its read-only owner may read
A server-side renderer, a static build, a search indexera personal API key of a dedicated usergraphql:readruns on your server; can read unpublished parts only if its owner may
An importer, a sync job, an editorial toola personal API key of a dedicated usergraphql:read,graphql:writemutations need graphql:write; give the owner only the policies the job needs
A mobile or desktop app where each person signs inan OAuth token (authorization code with PKCE)the person's rightseach person acts as themselves; tokens expire and refresh
An editor's tool inside the administrationthe sessionthe playground and /graphql/query
A webhook receiver that needs more datathe event itself, or Payload=query with QueryUserthe server runs a persisted query as that user and sends the answer

Never put a key that can write, or a key whose owner may read unpublished content, into code that runs in a browser or an app package. Anybody can read it there. The only key meant to be shipped is a public read key.

Anonymous access

A request without Authorization runs as the anonymous user (site.ini [UserSettings] AnonymousUserID), with the role Anonymous as assigned in that siteaccess. That role usually reads the public sections of the site.

  • Queries: everything Anonymous may read; the rest is null or left out.
  • Introspection: refused by default (Introspection=signed-in); allow it with Introspection=enabled on a public development siteaccess only.
  • Mutations: refused (FORBIDDEN "Sign in to change content.") unless AnonymousMutations=enabled (a guest book; the policies of Anonymous still decide), or every root field of the mutation is one a schema extension opens to anonymous callers (expGraphQLMutationExtension::anonymousMutationFields()).
  • Subscriptions: refused unless AnonymousSubscriptions=enabled.
  • Rate limit: RateLimitAnonymous (120 per 60 s) per IP address. Behind a proxy or a CDN make sure the kernel sees the client's address (trusted proxies), or every visitor shares one budget.
  • Response cache: anonymous answers of persisted queries are shared by every anonymous visitor and served before the kernel starts.
  • PersistedQueriesOnly=anonymous limits anonymous clients to the queries you persisted: nobody can send expensive queries of their own.

Personal API keys

A personal API key belongs to one user and acts as that user, limited to its scopes:

expk_du8hrkekh7wy_Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7cDe0f
└─┬┘ └────┬─────┘ └──────────────────┬───────────────────┘
prefix  12 lower-case                40 letters and digits:
        letters/digits:              the secret, never stored
        the key's id                 (only an HMAC-SHA-256 with a salt of its own)
  • 58 characters. The page or the command that makes it shows it once; it is never stored in readable form.
  • It has a name, scopes, optional siteaccesses, an expiry (rest.ini [ApiKeySettings] ExpiryChoices[]: 7, 30, 90, 365 days, or none where MaxExpiryDays=0), and records when and from which address it was last used (at most once a minute, LastUsedInterval).
  • It is checked on every request: well-formed, known, the secret matches (in constant time), not revoked, not expired, the owner enabled and not locked by failed logins, the siteaccess allowed, under its rate limit; then the route's scope, and that the owner still holds the scope's policy.
  • It is stored in the table expapikey (id, user_id, name, key_prefix, secret_hash, salt, scopes, created, created_by, expires, last_used, last_ip, revoked, revoked_by).

The full guide to keys, including the user pages and the REST routes, is Personal API keys.

Scopes

A scope names a policy the owner needs (rest.ini [ApiKeySettings] Scopes[]), checked when the key is made and again on every request. The scopes of the GraphQL API:

ScopeNeeds the policyAllows
graphql:readcontent/readqueries at /api/graphql, subscriptions at /api/graphql/subscribe
graphql:writecontent/editmutations (together with graphql:read, which the route needs); each mutation still checks the owner's policies on the content it changes

The route /api/graphql needs graphql:read (RouteScopes[expGraphQLRestController_query]); a key without it answers 403 insufficient_scope before GraphQL runs. A mutation with a key without graphql:write answers FORBIDDEN ("The API key has no scope graphql:write."). Other scopes (read, publish, edit, remove, help, migration:read) belong to other REST routes; give a GraphQL key only the GraphQL scopes.

Keys limited to siteaccesses

A key may be limited to siteaccesses: it is then refused (401 invalid_token, audit reason siteaccess) in every other siteaccess, whether chosen by host or by X-Siteaccess. Use it so a front-end key can never read in the editing siteaccess, where more content may be visible.

./console exp:graphql:keys --create --for=frontend --scope=graphql:read --key-siteaccess=site,site_de --apply

The limit is stored as siteaccess:<name> entries in the key's scopes column and is fixed when the key is made: to change it, make a new key and revoke the old one. The response cache keeps the limit with a remembered credential, so an early answer never serves a limited key an answer made in another siteaccess.

Public read keys

A public read key is the one kind of key designed to be shipped in a browser or an app. The kernel refuses to make one unless:

  • its only scope is graphql:read (it can never send a mutation or use another REST route);
  • it is limited to at least one siteaccess;
  • its owner only reads: no content/create, content/edit or content/remove of any kind. Create a dedicated user (for example frontend-reader) whose roles grant content/read on what the public may see, and nothing else. A role assigned later is not checked again: keep that account read-only.

It has its own rate limit, RateLimitPublicKey (3000 per RateLimitWindow), shared by every visitor of the front end, instead of each visitor's address counting under RateLimitAnonymous.

./console exp:graphql:keys --create --for=frontend-reader --scope=graphql:read --key-siteaccess=site --public --apply
# or while switching the API on:
./console exp:graphql:enable --siteaccess=site --key-for=frontend-reader --key-public --apply

Important

Every key, public ones included, is also counted by the REST layer's own key limit, rest.ini [ApiKeySettings] RateLimitPerMinute (120 a minute by default, counted in APCu per PHP-FPM pool or Velocity server; not enforced without APCu). Requests answered early from the GraphQL response cache never reach it, but uncached requests do. For a public key in front of a busy site, raise RateLimitPerMinute (it applies to every key) or set it to 0, and rely on RateLimitPublicKey.

A public read key is still a secret in one sense: anyone who copies it gets your front end's budget. Revoke and replace it when it is abused; the front end needs a deploy with the new key.

Creating keys

WhereWhoHow
The user's page API access (/apikey/list, linked from My account)the user, with the policy apikey/createname, scopes (only those the user's rights allow), siteaccesses, lifetime; shown once
The consolean operator./console exp:graphql:keys --create --for=<login> --name='...' --scope=graphql:read[,graphql:write] [--key-siteaccess=a,b] [--public] [--days=90] --apply
While switching onan operator./console exp:graphql:enable --siteaccess=site --key-for=<login> [--key-limited] [--key-public] [--scope=...] [--days=...] --apply
Setup > GraphQLan administrator with graphql/administratelists the API keys of every user
Setup > oAuth admin > API keys (/oauthadmin/keys)oauthadmin/*every key of every user: filter, search, revoke

Without --apply the console only shows what it would do. --days takes one of ExpiryChoices[] (default 90). A user may have at most MaxKeysPerUser (10) active keys. Making and revoking are recorded in the audit (access.apikey.create, access.apikey.revoke).

./console exp:graphql:keys                                    # every key with a GraphQL scope
./console exp:graphql:keys --list --format=json
./console exp:graphql:keys --create --for=indexer --name='Search indexer' --scope=graphql:read --days=365 --apply
./console exp:graphql:keys --create --for=importer --name='Product import' --scope=graphql:read,graphql:write --days=30 --apply

Store the key where your platform keeps secrets (an environment variable from a secret manager, never a file in the repository), and name it after its use (EXPONENTIAL_API_KEY, EXPONENTIAL_WRITE_KEY).

Rotating keys

Rotate every key on a schedule shorter than its lifetime, and at once when it may have leaked. Rotation without downtime:

  1. Make a second key with the same owner, scopes and siteaccesses (--create ... --apply).
  2. Put the new key into the program's secret store and deploy.
  3. Check that the new key is used: ./console exp:graphql:keys --list shows its last used time; the old key's stops moving.
  4. Revoke the old key: ./console exp:graphql:keys --revoke=expk_<old id> --apply.
KeySuggested lifetimeRotation
public read key365 daysyearly, with a front-end deploy
server read key (SSR, builds)90 daysevery 60 to 80 days
writing key (imports)30 daysevery 20 to 25 days, or per migration project
a person's tool7 to 30 dayswhen the task is over

A key nearing its end shows Expires soon (seven days before) on the API access page and in the administration. Automate the reminder: exp:graphql:keys --list --format=json gives each key's expiry.

Rotating the installation's secret key (EXP_SECRET_KEY or var/secrets/exp_secret.key) does not touch API keys; it ends every preview token and every secret stored in the secret store (webhook signing secrets included).

Revoking keys and incident response

./console exp:graphql:keys --revoke=expk_du8hrkekh7wy --apply      # by prefix (or by id)

A revoked key is refused from the next request on, on every server: the REST layer reads the table on every request. The response cache's credential cache forgets a key at once when a key changes, so no early answer serves it either. A revoked key stays listed as Revoked and cannot be made valid again.

When a key leaked:

  1. Revoke it now.
  2. Read what it did: the audit (Setup > Audit trail) records first use (access.apikey.use), refusals (access.apikey.use.failed with the reason), and every mutation (content.graphql.mutation) with the key.
  3. Make a new key and deploy it.
  4. If it could write, review the content it changed (the audit names the objects), and restore versions where needed.

OAuth tokens

For apps where people sign in, the REST layer's OAuth server issues tokens:

GET  /oauth/authorize?client_id=...&redirect_uri=...&response_type=code&state=<random>
     &code_challenge=<BASE64URL(SHA256(verifier))>&code_challenge_method=S256
-> 302 <redirect_uri>?code=<code>&state=<random>

POST /api/auth/v1/oauth/token
     grant_type=authorization_code&client_id=...&code=<code>&redirect_uri=...&code_verifier=<verifier>
-> {"access_token": "...", "refresh_token": "...", "expires_in": 3600}

Send the access token as Authorization: Bearer <token>. It expires after rest.ini [OAuthSettings] TokenTTL (one hour by default); refresh it with grant_type=refresh_token. Register the app at Setup > oAuth admin > Applications. PKCE and state are described in PKCE and state for the OAuth server.

With the SDK:

import { bearerToken, createClient } from '@exponentialcms/client';

const client = createClient({
  url: 'https://www.example.com',
  auth: bearerToken(() => session.accessToken, async () => session.refresh()),   // refreshed once after a 401
});

The session of the administration

The playground of Setup > GraphQL and the session end point POST /graphql/query run with the browser session of a signed-in editor (policies graphql/playground and graphql/query). Queries need nothing more; mutations need the form token of the session in the header X-CSRF-Token (or the form field ezxform_token), so a page of another site cannot make the editor's browser change content. The session end point always accepts ad-hoc queries, even where PersistedQueriesOnly is set.

Roles and policies you need

WhoPolicies
The anonymous usercontent/read on what the public may see (the role Anonymous)
The owner of a read keycontent/read (limited to the sections or subtrees the client may see), and apikey/create to make keys on the user page
The owner of a public read keythe above, and no content/create, content/edit, content/remove
The owner of a writing keycontent/read, content/edit; content/create for the classes and places it creates; content/publish where the workflow requires it; content/remove to delete; content/hide to hide and reveal; for a move content/edit and content/remove at the old place and content/create at the new one; section/assign, state/assign, content/restore for those mutations; content/versionread to read others' drafts
An editor using the playgroundgraphql/playground, graphql/query
An administrator of the APIgraphql/administrate (switches, cache, persisted queries, keys in Setup > GraphQL)
The migrations queriesmigration/read
Who may make keys at allapikey/create (with a Scope limitation listing the scopes allowed); no role has it in a new installation

Grant the narrowest limitation that works: a subtree limitation for a key that only reads the blog, a class limitation for a key that only creates products. A key never gets a right its owner does not hold.

What happens when a credential is refused

SituationAnswerAudit (access.apikey.use.failed reason)
key malformed401 {"error":"invalid_token"}malformed
key unknown401 invalid_tokenunknown
secret wrong401 invalid_tokensecret
key revoked401 invalid_tokenrevoked
key expired401 expired_tokenexpired
owner disabled, anonymous, or locked after failed logins401 invalid_tokenowner
key limited to other siteaccesses401 invalid_tokensiteaccess
key over RateLimitPerMinute429 rate_limited (with Retry-After)rate_limited (once a minute)
key sent in the query string or body401 invalid_tokentransport
key without graphql:read403 insufficient_scopescope
owner lost content/read403 insufficient_scopepolicy
keys switched off (ApiKeys=disabled)401 invalid_token
OAuth token expired401 expired_token
GraphQL rate limit429 RATE_LIMITED (GraphQL error body)
mutation without graphql:write200 FORBIDDENcontent.graphql.mutation.failed, reason scope

The SDK's bearerToken(..., refresh) refreshes once after a 401; an apiKey() client reports ExponentialHttpError with status 401: fix the key, do not retry.

Security guidance

  • One key per client and environment. Never share a key between staging and production or between two programs.
  • Dedicated users. Keys belong to service users (frontend-reader, indexer, importer), not to people. When a person leaves, their keys must not run your site.
  • Smallest scope, narrowest policy, shortest lifetime. graphql:write only for programs that write.
  • Limit front-end keys to the front-end siteaccess. An editing siteaccess may show more content.
  • Never in URLs, logs or the repository. The kernel refuses keys in query strings; keep them out of your own logs (mask Authorization in request logging, as the SDK's middleware lets you).
  • HTTPS only. A key or token over plain HTTP can be read by anyone on the way.
  • Read-only public siteaccess. For a siteaccess that only serves visitors, MutationsEnabled=disabled (./console exp:graphql:disable --siteaccess=<name> --mutations --apply).
  • Lock anonymous clients to your queries with PersistedQueriesOnly=anonymous.
  • Keep introspection signed-in in production (Introspection=signed-in, the default).
  • Keep Debug=disabled in production: debug output contains paths and code.
  • Watch the audit. Refusals with reason secret or unknown from one address are someone guessing.
  • Mutations are audited per user: a key per program makes the audit say which program changed what.

Settings

SettingDefaultMeaning
rest.ini [ApiKeySettings] ApiKeysenabledkeys accepted and made at all
ExpiryChoices[]7, 30, 90, 365, 0lifetimes offered (0: never; only with MaxExpiryDays=0)
DefaultExpiryDays / MaxExpiryDays90 / 365
MaxKeysPerUser10active keys per user; 0 no limit
LastUsedInterval60seconds between writes of last use
RateLimitPerMinute120per key, in APCu; 0 no limit
Scopes[graphql:read], Scopes[graphql:write]content/read, content/editthe policy behind each scope
RouteScopes[expGraphQLRestController_query], [..._subscribe]graphql:readthe scope the routes need
graphql.ini [GraphQLSettings] Introspectionsigned-inwho may read the schema
AnonymousMutations / AnonymousSubscriptionsdisabled
RateLimit / RateLimitAnonymous / RateLimitPublicKey / RateLimitWindow600 / 120 / 3000 / 60
CredentialCacheTtl60seconds the response cache remembers a credential's rights
PreviewTokenTtl / MaxPreviewTokenTtl3600 / 86400

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x