Module for Apostol CRM1.
Auth Server is a C++ OAuth 2.0 Authorization Server module for the Apostol (C++20) framework. It runs inside Apostol worker processes and handles all requests under the /oauth2/ path prefix.
Key characteristics:
- Written in C++20 using an asynchronous, non-blocking I/O model based on the epoll API.
- Implements RFC 6749 (OAuth 2.0), OpenID Connect, and RFC 7519 (JWT). Supported grant types: Authorization Code, Implicit, Resource Owner Password Credentials, Client Credentials, Token Exchange (RFC 8693), and JWT Bearer.
- All token issuance and session management logic runs in the database (
daemon.token,daemon.login). The C++ layer handles only HTTP transport, parameter validation, JWT signature operations, and cookie management. - JWT verification is done locally using the
jwt-cpplibrary — all 12 algorithms (HS256/384/512, RS256/384/512, ES256/384/512, PS256/384/512) are supported without a database round-trip. - Supports external identity providers (Google, ESIA) via standard JWKS certificate endpoints, with public keys fetched and cached in memory.
- Simplifies user access by allowing sign-in through existing accounts (e.g. Google) without requiring a separate registration step.
AuthServer registers itself as the handler for any request whose path starts with /oauth2/ (see CheckLocation). It accepts GET, POST, and OPTIONS; all other HTTP methods return 405 Method Not Allowed.
GET /oauth2/{action} routing:
| Action | What C++ does | Database call |
|---|---|---|
authorize / auth |
Validates client_id, redirect_uri, response_type, scope, access_type, prompt. The client is looked up among clients of the default provider only. Then: with a live session (cookie SID, or the sub claim of __Secure-AT), response_type=code and no screen-naming prompt — asks the database for a code. It answers consent_required unless the user has already granted this client the requested scopes, in which case the browser goes to oauth2.consent; otherwise the code is issued and the browser redirected to redirect_uri?code=&state=. With prompt=consent — straight to oauth2.consent. Otherwise — to the login page (oauth2.identifier or oauth2.secret). |
daemon.authorization_code(session, client_id, redirect_uri, scope, state, access_type, agent, host, consent) (only when a session is present) |
code |
Receives authorization code from external provider redirect. For external providers (e.g. Google): makes a direct C++ HTTP call to the provider's token_uri to exchange the code for a token, then verifies the returned JWT. |
daemon.login(token, agent, host, origin) |
callback |
Redirects to oauth2.callback from conf/sites/*.json. |
None |
identifier |
Extracts value from request body. Authenticates via: (1) Authorization: Bearer header, (2) Session+Secret headers, (3) cookie __Secure-AT/__Secure-SAT selected by X-Auth-Context, or (4) nothing at all — the login and registration screens ask this before anyone has signed in, so the module answers using its own service token (see below). |
daemon.identifier(token, value) |
POST /oauth2/{action} routing:
| Action | What C++ does | Database call |
|---|---|---|
token |
Parses client_id/client_secret from body or Authorization: Basic header. For the web app sent without a secret: validates redirect_uri and javascript_origins against provider config and fills the secret in; never for service, whose callers send it. Without a secret otherwise, only authorization_code and refresh_token of a client of this installation go on to the database, which accepts them from a public client only (see Public clients and PKCE); every other grant is 400 invalid_request. Parameters are read from the body only: an empty body is 400 invalid_request, whatever the query string holds. Calls DB with full payload as JSONB. |
daemon.token(client_id, client_secret, payload::jsonb, agent, host) |
consent |
The answer to the consent screen. Requires a request body, a response_type of code, a live session, and a double-submit token: the __Host-CT cookie must equal the consent_token field. Records the consent, then issues the code and redirects to redirect_uri?code=&state=. |
daemon.authorization_code(…, consent := true) |
identifier |
Same as GET identifier. | daemon.identifier(token, value) |
revoke |
Closes the session a token belongs to — that session only. With a body it is RFC 7009 token revocation: token in the body (never the query string), an access, refresh or id token; token_type_hint is accepted and searched past (§2.1) — daemon.session_revoke (db-platform 1.2.32 or later) looks the token up among live access, refresh and id tokens; a token found closes its session and every token issued with it; no cookie is touched. 200 with an empty body whether the token was revoked or is unknown, expired, revoked already or an authorization code (§2.2) — an expired access token therefore leaves its session alive: to end it, send the refresh token; 400 invalid_request for a token that contains a space (a + sent unencoded in a form body decodes to one — send it as %2B) or any other byte outside printable ASCII (a trailing line feed among them), or is longer than 8192 bytes; 503 temporarily_unavailable on any failure, the token then to be taken as still valid (§2.2.1). Without a body it is the browser's sign-out: the pair is read from __Secure-AT/__Secure-RT, with a refresh token present the pair first goes through daemon.refresh_token — an expired access token cannot close its session, and the database, not this host's clock, decides whether it has expired, and every credential cookie is erased on the answer. The browser form requires __Host-SID (SameSite=Lax, so a cross-site POST arrives without it) and, where the browser sends it, Sec-Fetch-Site: same-origin or none (Lax still rides along from a sibling subdomain); otherwise 400 with the cookies left alone. No client authentication — holding a token of the session is the entitlement. The browser form answers 200 with an empty body when the session is closed or the token is not a live one (RFC 7009 §2.2), 503 temporarily_unavailable when the database could not be asked. Either form answers 503 when the database has not answered within 10 s. |
daemon.session_revoke(token, hint) (body form); daemon.refresh_token(token, refresh) (browser form with a refresh token), then daemon.session_close(token) (browser form) |
Identifier endpoint authentication priority:
Authorization: Bearer <JWT>header — token verified locally via jwt-cppSession+Secretheaders — inter-service authentication (session ID passed directly)- Cookie-based — reads
X-Auth-Contextheader: if"service"→__Secure-SATcookie, otherwise →__Secure-ATcookie. Token from cookie is verified locally via jwt-cpp.
Token endpoint flow (POST /oauth2/token) step by step:
- The worker's event loop (epoll) accepts the connection and reads the HTTP request.
AuthServerparses the grant type and client credentials from the request body orAuthorization: Basicheader. For thepasswordgrant without an explicitclient_id, the default web application client is used automatically.- For the
webapplication sent without a secret: C++ validatesredirect_uriandjavascript_originsin-process and fills the secret in (never forservice— its callers are servers and send it) against the provider configuration loaded fromconf/oauth2/— no database query needed for these checks. - It calls
daemon.token(client_id, client_secret, payload, agent, host)asynchronously. The database handles all grant type logic: token generation, session creation, refresh tokens, token exchange, and external JWT validation. - On success: C++ sets three
HttpOnlycookies (__Secure-AT,__Secure-RTwith 60-day TTL andSameSite=None; Secure;SIDsession cookie) and returns the JSON token response to the client.
Successful and error responses from POST /oauth2/token carry Cache-Control: no-store and Pragma: no-cache.
JWT handling in C++:
The module uses the jwt-cpp library directly for all cryptographic operations:
- Verification — supports all 12 algorithms. For HMAC algorithms (HS256/384/512) the secret is read from the provider config. For asymmetric algorithms (RS*/ES*/PS*) the public key is looked up by
kidfrom the in-memory JWKS cache. After asymmetric verification, the token is re-signed with HS256 for uniform internal handling. - Creation — issues a short-lived HS256 token (1-hour TTL) signed with the
webapplication secret, with issuer and audience taken from the default provider config.
Heartbeat (runs every 30 minutes):
Heartbeat() resets all provider key statuses to ksUnknown, then fetches fresh JWKS/certificate public keys from each provider's cert_uri via a non-blocking C++ HTTP client. On fetch failure, the next retry is scheduled in 5 seconds instead of 30 minutes. Cached keys are used by VerifyToken() to validate RS*/ES*/PS* signatures without a round-trip to the database.
AuthServer is tightly coupled to the oauth2 and admin modules of db-platform.
All authentication state lives in the database — the C++ module handles only HTTP transport and local JWT signature validation:
| Object | Module | Purpose |
|---|---|---|
| OAuth2 clients | oauth2 |
Registered applications with client_id / client_secret |
| OAuth2 providers | oauth2 |
External identity providers (Google, ESIA, etc.) with JWKS/cert URIs |
| OAuth2 audiences | oauth2 |
Token audiences linked to clients |
| Authorization codes | oauth2 |
Short-lived codes for the Authorization Code flow |
| Sessions | admin |
User sessions created on successful authentication |
| Users / passwords | admin |
User accounts, credential validation |
All grant type logic (token issuance, refresh, exchange, validation) is implemented as PL/pgSQL functions called by the module. Provider public keys are fetched from external URLs and cached locally by the C++ module (refreshed every 30 minutes).
For frontend developers — getting a token requires exactly two possible requests.
All tokens are issued by a single endpoint. The Authorization: Basic header carries client_id:client_secret encoded in Base64. As RFC 6749 §2.3.1 requires, client_id and client_secret are form-urlencoded before they are joined and Base64-encoded, and the server decodes them: + reads as a space and %XX as its byte, so a secret containing + or % must be sent encoded. Your client_id, client_secret, and scope are provided by the server owner. The body must be an object; grant_type, client_id, client_secret and redirect_uri must be strings, or the answer is 400 invalid_request.
Use client_credentials for backend integrations and service-to-service calls. Token lifetime: 24 hours.
Request:
POST /oauth2/token HTTP/1.1
Host: YOUR-HOST
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <base64(client_id:client_secret)>
grant_type=client_credentials&scope=YOUR-SCOPE&access_type=offlineResponse 200 OK:
{
"access_token": "eyJ...",
"refresh_token": "mZfA...",
"secret": "n9RX...",
"token_type": "Bearer",
"expires_in": 86400,
"session": "db17c81d..."
}Authenticates a specific user. Token lifetime: 1 hour.
Request:
POST /oauth2/token HTTP/1.1
Host: YOUR-HOST
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <base64(client_id:client_secret)>
grant_type=password&username=USER&password=PASS&scope=YOUR-SCOPE&access_type=offlineResponse 200 OK:
{
"access_token": "eyJ...",
"refresh_token": "85Hr...",
"secret": "0NTZ...",
"token_type": "Bearer",
"expires_in": 3600,
"session": "ca8db8e7..."
}Use access_token as a Bearer token in all subsequent API requests:
Authorization: Bearer eyJ...
The server sets HttpOnly cookies automatically:
| Grant type | Cookies set |
|---|---|
password, authorization_code, refresh_token, jwt-bearer |
__Secure-AT, __Secure-RT, SID (user session) |
client_credentials |
__Secure-SAT, __Secure-SRT (service session, no SID) |
Full reference: Authentication and Authorization
For browser SPA developers — zero token management code required.
The server implements the Token Handler pattern out of the box. Two independent cookie pairs coexist for different auth contexts:
| Context | Cookies | Set on | Use case |
|---|---|---|---|
| User | __Secure-AT, __Secure-RT, SID |
password / authorization_code login |
Authorized user operations |
| Service | __Secure-SAT, __Secure-SRT |
client_credentials grant |
Public/guest operations (registration, public data) |
All cookies are HttpOnly; Secure; SameSite=None. The browser sends them automatically — the frontend never reads or manages tokens directly.
User context (default):
Browser SPA
└─ fetch('/api/v1/...', { credentials: 'include' })
↓
Apostol AppServer
1. Reads __Secure-AT from cookie
2. Verifies token — if expired:
a. Calls daemon.refresh_token() → new tokens
b. Sets new __Secure-AT, __Secure-RT, SID cookies
c. Replays the original request transparently
3. Returns API response + Set-Cookie headers
Service context — frontend sends X-Auth-Context: service header:
Browser SPA
└─ fetch('/api/v1/...', { credentials: 'include', headers: { 'X-Auth-Context': 'service' } })
↓
Apostol AppServer
1. Reads X-Auth-Context header → selects __Secure-SAT cookie
2. Verifies token — if expired:
a. Calls daemon.refresh_token() → new tokens
b. Sets new __Secure-SAT, __Secure-SRT cookies
c. Replays the original request transparently
3. Returns API response + Set-Cookie headers
Both pairs live in the browser simultaneously and do not conflict.
- Add
credentials: 'include'to every request. - Send
X-Auth-Context: serviceheader for service (guest/public) requests.
// 1. Service auth (once, before user login — e.g., on registration page)
await fetch('/oauth2/token', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'grant_type=client_credentials&client_id=CLIENT&scope=SCOPE'
});
// Cookies __Secure-SAT, __Secure-SRT are set automatically.
// 2. Service API calls (public data, registration, etc.)
const data = await fetch('/api/v1/sign/up', {
method: 'POST',
credentials: 'include',
headers: { 'X-Auth-Context': 'service' },
body: JSON.stringify({ username: 'new_user', ... })
});
// 3. User login
await fetch('/oauth2/token', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'grant_type=password&username=USER&password=PASS&...'
});
// Cookies __Secure-AT, __Secure-RT, SID are set automatically.
// 4. User API calls (default context, no extra header needed)
const profile = await fetch('/api/v1/whoami', { credentials: 'include' });
// Token refresh is transparent — you always get a 200.A 401 Unauthorized means the session has completely expired (both access and refresh tokens are invalid). Redirect to login:
if (response.status === 401) {
window.location.href = '/login';
}| Do NOT | Why |
|---|---|
Store tokens in localStorage / sessionStorage |
Vulnerable to XSS; cookies are HttpOnly — JS cannot read them |
Track expires_in and schedule a refresh |
AppServer refreshes transparently on every expired request |
| Write refresh logic | Already handled server-side |
Send Authorization: Bearer header |
Not needed when using cookies (both modes are supported simultaneously) |
CORS is enforced by an origin allowlist loaded from conf/oauth2/*.json (javascript_origins fields). Requests from unknown origins do not receive Access-Control-Allow-Credentials: true, so the browser blocks cross-origin cookie sending from untrusted sites.
To allow your frontend origin, add it to javascript_origins in your provider config:
{
"web": {
"javascript_origins": [
"https://your-app.com",
"http://localhost:3000"
]
}
}The protocol defines four roles:
- Resource owner — the user of the system (a natural person);
- Client — the application that requests access to a protected resource on behalf of its owner;
- Authorization server — the server that issues identity tokens with the resource owner's permissions to the client, as well as access tokens that allow access to data;
- Resource server — the server that provides access to the protected resource based on verification of identity tokens and access tokens (for example, to user identity data).
In this implementation, the authorization server and the resource server are the same server.
To interact with the server, a Client must obtain a client identifier (client_id) and a client secret (client_secret).
All interaction occurs through the RESTful API described in the RFC 6749 specification.
The general authentication flow using OpenID Connect is as follows:
- The Client prepares an authentication request with the required parameters;
- The Client sends a
GETrequest to the authorization server; - The Authorization server authenticates the user (the user enters their username and password);
- The Authorization server obtains the user's consent to authenticate within this system;
- The Authorization server redirects the user back to the Client and provides an authorization code;
- The Client sends a
POSTrequest using the authorization code to obtain an identity token; - The Client receives a response containing the required identity token (exchanges the authorization code for an access token);
- The Client validates the identity token and extracts the user identifier from it.
The sections below describe in detail the requests formed by the Client and the responses returned by the Authorization Server.
For authorization:
GET /oauth2/authorizeFor recording the user's consent:
POST /oauth2/consentFor obtaining an access token:
POST /oauth2/tokenFor signing in by a one-time code from a first-party application (see Sign-in by a one-time code):
POST /oauth2/challengeGET /oauth2/authorize hands an authorization code straight to the client when the
user is already signed in — no password, no second login. Two conditions gate it,
and both are enforced in daemon.authorization_code, not in this module:
-
The client must belong to an internal provider. An entry in
conf/oauth2/google.json— or a row inoauth2.audienceunder an external provider — registers that provider so its tokens can be verified. It does not make its holder a client of this installation, and it yields no codes for local users. Only clients of thedefaultprovider reach this path. -
The user must have granted this client consent covering the requested scopes (
db.oauth2_consent). Being registered is not being permitted. Without a standing consent the database answersconsent_requiredand the browser is sent to the consent screen instead.
Behaviour change (db-platform 1.2.11). Before this, a signed-in browser arriving at
/oauth2/authorizewas handed a code with nothing asked of the user, and anyclient_idpresent inconf/oauth2/*.json— under any provider — was enough. Existing deployments will now show the consent screen once per client per user — provided the site namesoauth2.consent. Where it does not, the branch answersconsent_requiredon the client'sredirect_uriinstead of issuing a code: closed, and visibly so. See Consent screen location below.
POST /oauth2/consent is the answer to that screen. It records the consent and then
issues the code exactly as the authorize endpoint would have.
It is a POST, and it carries a double-submit token. The consent screen mints a
random value, keeps it in a SameSite=Strict, __Host- prefixed cookie and repeats
it in the form body; the endpoint requires the two to match. This is what separates
the user's own click from a third-party page acting in their name — a signed-in
browser carries its cookies wherever it is sent, and __Secure-AT is SameSite=None,
so it rides along on a cross-site POST as well.
Do not replace this with an
Origincheck. It looks like the natural guard and it is inert here: the deployment recipe these projects ship rewrites the header on every/oauth2/request —location ^~ /oauth2/ { proxy_set_header Origin "https://$host"; }— so by the time the request arrives,Originreads as the server's own whoever sent it. That substitution cannot simply be removed either: handing the web client itsclient_secretinPOST /oauth2/tokenis built on it.
The consent screen and the authorization server must be served from the same
origin. The module's own SPA assumes this (VITE_API_HOST empty), and the cookie
guard depends on it.
The session cookies stay
SameSite=None, and that is not an oversight. It is what makes single sign-on possible at all: arriving at/oauth2/authorizefrom a client's site is a cross-site top-level navigation, and underSameSite=Strictthe browser would withhold the session, so the user would look signed out and the flow would never start. Tightenset_secure_cookiesand you do not harden this endpoint — you disable the feature.__Host-CTcan affordStrictprecisely because it is minted and spent within one origin.
The page is named by oauth2.consent in conf/sites/*.json:
{
"hosts": ["auth.example.com"],
"root": "/opt/example/www",
"oauth2": {
"identifier": "/login",
"consent": "/authorize",
"error": "/error"
}
}This key is required for the single sign-on branch to work. There is no fallback
path on purpose: the module would have to guess a URL on whichever host the request
arrived at, and the screen exists only on the host that serves the SPA. A site
without oauth2.consent answers consent_required on the client's redirect_uri
instead — visible to whoever integrates, rather than a redirect into a 404.
The module's own SPA serves the screen at /authorize.
Apply the database patch and deploy the binary together. The two halves do not work apart, and each failure is quiet in its own way:
| Order | What happens |
|---|---|
| Patch applied, old binary still running | P00000011 drops the eight-argument daemon.authorization_code; the old binary still calls it with eight and gets function does not exist → 500 on the sign-on branch |
| New binary, patch not applied | db.oauth2_consent is missing. The routine detects this and answers server_error with "The authorization server is not fully migrated", and writes the patch number to the event log |
Routines updated without the patch (runme.sh --update alone) |
Same as above. --update reloads routines but creates no tables; the patch is what creates the consent table and drops the old signature |
Note that a database that has the new routines but not the patch still has the
old eight-argument function unless the patch ran — and that function issues codes
without asking anyone. Updating routines alone does not close the hole; applying the
patch does. After migrating, \df daemon.authorization_code must show exactly one
row.
POST /oauth2/identifier may be called with no credentials. That is not a relaxation:
the screen that calls it — "is this address already registered?" — runs before anyone
has signed in, and the page has nothing it could authenticate with.
RFC 6749 §2.1 classifies a browser-based application as a public client, "incapable of maintaining the confidentiality of their credentials", and §4.4 states that "the client credentials grant type MUST only be used by confidential clients". A page therefore cannot hold a client secret, whatever it does with it — a secret shipped to a browser is readable in the developer tools, the bundle and the network tab. RFC 10017 (BCP 212) §6.1 names the pattern that replaces it: a backend that "interacts with the authorization server as a confidential OAuth client" on the page's behalf.
So the module holds an access token of its own — ServiceToken, obtained with the
client credentials grant using the service client from conf/oauth2 and refreshed
from heartbeat() — and uses it for this call. Previously the page obtained that
token itself, which meant the server would hand a service credential to anybody who
asked for one.
No new capability appears here — the endpoint was already open to any caller
willing to mint a token first. What does disappear is the cost of a probe and the
trail it left: minting a token wrote rows to db.session and db.token, so misuse
was visible and countable; an anonymous POST writes nothing. Rate-limiting this route
is now the only control over identifier enumeration — apply the recipe below to
/oauth2/identifier as well as /oauth2/consent.
Requires a service entry in conf/oauth2/default.json. Unauthenticated callers get
503 temporarily_unavailable whenever no token is held: for about a second after a
worker starts or is restarted by SIGHUP, while the database is unreachable, and for
as long as refreshes keep failing. Authenticated callers are unaffected.
Partly presented credentials are now ignored rather than refused: a Session header
without Secret, or X-Auth-Context: service without the __Secure-SAT cookie, used
to give 401 and now falls through to the anonymous path.
Rate-limit the endpoint. POST /oauth2/consent is anonymous and reachable
without a session, and every refusal writes a line to the log. Under the usual nginx
recipe the route falls under the general ^~ /oauth2/ block, which typically has no
limit of its own — an exact-match location wins over the prefix:
limit_req_zone $binary_remote_addr zone=auth_consent:10m rate=10r/m;
location = /oauth2/consent {
limit_req zone=auth_consent burst=5 nodelay;
proxy_pass $backend_upstream;
# keep the Origin rewrite from the surrounding block — POST /oauth2/token
# depends on it; the consent guard deliberately does not.
}redirect_uri is compared to the client's registered values exactly, string for
string. This is deliberate — do not "improve" it into a prefix or normalising match.
A prefix comparison turns one registered https://app.example.com/cb into a licence
for https://app.example.com/cb.attacker.com, and normalisation invites the whole
family of URL-parsing disagreements between the checker and the browser.
OAuth 2 defines four standard authorization grant types, each suited to different use cases, plus two extended grant types supported by this implementation:
- Authorization Code — used with server-side applications.
- Implicit — used with mobile or web (JavaScript) applications running on the user's device.
- Resource Owner Password Credentials — used with trusted applications that are part of the service itself.
- Client Credentials — used when the client (application) accesses the API without a user authorization context.
- Token Exchange (RFC 8693) — used to obtain a new access token before the current one expires.
- JWT Bearer — used to authenticate using a JWT token issued by an external system (e.g., Google). Disabled by default; see JWT Bearer Grant.
A native application cannot keep a client secret: anything shipped inside it can be read out of it. Such a client
is registered as public — a flag of its audience in the database (oauth2.audience.public_client, set by
kernel.SetAudiencePublicClient; off for every client by default). A public client signs a user in with the
authorization code flow and PKCE and sends no client_secret:
GET /oauth2/authorize?…&code_challenge=<S256 challenge>&code_challenge_method=S256;POST /oauth2/tokenwithgrant_type=authorization_code,client_id,code,redirect_uriandcode_verifierin the body;POST /oauth2/tokenwithgrant_type=refresh_token,client_idandrefresh_tokenin the body.
A public client's code is exchanged only with PKCE; password, client_credentials and the JWT bearer grant are
refused to it (400 unauthorized_client). A request without a secret from a client without the flag is
400 invalid_request, as before. Any client may use PKCE; a code issued with a challenge is exchanged only with its
verifier.
daemon.authorization_code is called with the challenge as an eleventh argument only when the request carries one,
so a module with PKCE answers requests without it on a database that predates PKCE as well. Update the database
first all the same: a PKCE request, and a public client, need it.
An application with its own sign-in screen (a first-party client) signs a user in by a code sent by SMS, without a
browser, a password or a client secret — the authorization challenge endpoint of
OAuth 2.0 for First-Party Applications.
A client may use it only when its audience carries the flag oauth2.audience.authorization_challenge (set by
kernel.SetAudienceAuthorizationChallenge; off for every client by default), and the client must be one this
installation issues (the default provider of its OAuth 2.0 configuration). Parameters go in the body only, as on
/oauth2/token; no client secret is asked for.
Use a dedicated native application entry in the default provider and set
oauth2.audience.public_client to true with kernel.SetAudiencePublicClient to exchange the
authorization code without a secret. The web entry uses browser origin validation.
Registration by SMS is off by default. To enable it, use kernel.SetAudienceChallengeRegistration on an
audience with authorization_challenge enabled. The database configuration must provide the internal
hooks kernel.ChallengeRegistrationDocuments() RETURNS json and
kernel.ChallengeRegistration(pPhone text, pName jsonb, pEmail text, pConsents text[], pHost inet, pAgent text) RETURNS uuid.
The registration hook must create a new account with the supplied canonical phone number, record the supplied
consents in the same transaction, and return the UUID of the new account.
POST /oauth2/challengewithclient_id,response_type=code,scope,code_challenge,code_challenge_method=S256(both required),login_hint(the phone number) and an optionalhashcode. The answer is the same whatever the number:403witherror=insufficient_authorization,auth_sessionandexpires_in. A code can be sent to a verified user phone number or, when registration is enabled, to an unrecognized number, subject to the site's registration SMS limit.POST /oauth2/challengewithclient_id,auth_sessionandotp(the code from the SMS). The right code:200withauthorization_codefor an existing account. When registration is enabled and an account must be created, the verified session stays open and the response is403 insufficient_authorizationwithregistration_required: true, the sameauth_session,expires_inanddocuments: [{code, type, name, text, required}]. A wrong code returns403 insufficient_authorization. An expired or spent session, or one out of attempts, returns400 invalid_session.- If registration is required,
POST /oauth2/challengeas JSON withclient_id, the sameauth_sessionandregistration: {name, email?, consents: [<code>, …]}. Omitotp.nameis a string of 1 to 100 characters after trimming, or an object{first, last?}with a non-emptyfirst; anything else returns400 invalid_request(Invalid parameter: registration). The configuration hook receives the name as sent. Use the codes fromdocumentsfor the documents the user accepts. A missing required code or a code outside the current list returns403 insufficient_authorizationwithregistration_required: true, the same session and a freshdocumentslist, without counting an attempt. With a valid session and current consents, a number already linked to any account returns403 access_deniedregardless of the linked number's verification status. This includes numbers linked after OTP verification and numbers stored in a legacy format. Clients use the freshdocumentslist to request updated consents and handleaccess_deniedas a registration refusal. An unverified, spent or expired session returns400 invalid_session. A 4xx refusal of the configuration's registration hook (for example an e-mail address that belongs to another account) returns400with{"error": "invalid_request", "error_code": "<ERR-GGG-CCC>", "error_description": "<text>"}: the work of the hook is undone, the verified session stays open, and the step can be repeated with other data and the sameauth_session, without another SMS. Each such refusal counts as an attempt of the session, like a wrong code: when the attempts are used up, the session returns400 invalid_sessionand a new code is requested. Success returns200withauthorization_code.
Exchange the authorization_code from step 2 or 3 at POST /oauth2/token with
grant_type=authorization_code, client_id, code and code_verifier. Omit redirect_uri and the
client secret. The response includes access_token, refresh_token and expires_in.
Code requests are limited per phone number and per client address; over the limit the answer is
429 slow_down with Retry-After. Every answer carries Cache-Control: no-store. The module relays the status and
the body that daemon.authorization_challenge returns; the statement is not written to the log. Update the database
first: on a database without the function the endpoint answers 500 server_error.
Authorization Code is one of the most commonly used grant types because it is well suited for server-side applications where the application source code and the client secret are not exposed to outside parties. The flow is redirect-based, which means the application must be able to interact with the user agent (e.g., a web browser) and receive authorization codes redirected through the user agent.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client (application) identifier. |
| redirect_uri | redirect_uri |
Required. The URI to which the authorization server will redirect the user agent (browser) along with the authorization code. |
| response_type | code | Required. Indicates that the application is requesting access using an authorization code. |
| scope | scope |
Recommended. A space-separated list of scopes that define the resources your application can access on behalf of the user. |
| access_type | access_type |
Recommended. Specifies whether your application can refresh access tokens when the user is not present in the browser. Accepted values: online (default) and offline. |
| state | state |
Recommended. A set of random characters that will be returned by the server to the client (used to protect against replay attacks). |
| prompt | prompt |
Optional. Controls the screen shown to the user. Accepted values: signin, secret (password page), consent, select_account, none. Omitted: a signed-in user gets a code without seeing any screen; otherwise the identifier page. secret — the password-entry page (oauth2.secret); consent — the consent screen (oauth2.consent); signin and select_account — the identifier page even when a session already exists. |
| code_challenge | code_challenge |
Optional; required for a public client. PKCE (RFC 7636): BASE64URL(SHA256(code_verifier)) without padding, 43 characters. Carried through the sign-in and consent screens and stored with the code. |
| code_challenge_method | S256 | Required with code_challenge. Only S256 is accepted; plain, any other value, a method without a challenge or a challenge without a method is answered with error=invalid_request on redirect_uri. |
Example request:
GET /oauth2/authorize?client_id=YOUR-CLIENT-ID&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcode&scope=api&response_type=code&access_type=online&state=c2FmZXR HTTP/1.1
Host: localhost:8080http://localhost:8080/oauth2/authorize?
client_id=YOUR-CLIENT-ID&
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcode&
response_type=code&
access_type=online&
scope=api&
state=c2FmZXR
If authentication succeeds, the authorization server will redirect the user to the URI specified in redirect_uri and return two mandatory parameters:
code— the authorization code;state— the value of thestateparameter that was sent in the authentication request.
The Client must compare the state value it sent with the value it received.
Authorization code response:
http://localhost:8080/oauth2/code?code=b%2F8NpjbB4eLaukGr68tE7maTCeBISO%2FC7hWxKGuKb8I4Ysc7uw8a2MRUMWnO3Nzt
- Note that the code (
b/8NpjbB4eLaukGr68tE7maTCeBISO/C7hWxKGuKb8I4Ysc7uw8a2MRUMWnO3Nzt) is URL-encoded and must be URL-decoded before use.
If an error occurs during authentication, the authorization server will redirect the user to the URI specified in redirect_uri with error information:
http://localhost:8080/oauth2/code?code=403&error=access_denied&error_description=Access%20denied.
To exchange the authorization code for an access token, the Client must form a POST request.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client identifier. |
| client_secret | client_secret |
Required. The client secret. |
| grant_type | authorization_code | Required. As defined in the OAuth 2.0 specification, this field must contain the value authorization_code. |
| code | code |
Required. The authorization code returned from the initial request. |
| redirect_uri | redirect_uri |
Required. The redirect URI (must match the redirect_uri from the initial request). |
| code_verifier | code_verifier |
Required when the code was issued with code_challenge, refused otherwise. 43–128 characters of [A-Za-z0-9._~-]. A wrong or missing verifier is 400 invalid_grant. |
- According to the OAuth 2.0 specification, the client authentication parameters (
client_idandclient_secret) may be passed either in the request body or in the HTTPAuthorizationheader (HTTP Basic authentication):
Authorization: Basic d2ViLXNlcnZpY2UucnU6Y2xpZW50IHNlY3JldA==
In response, the authorization server will return a JSON object containing a short-lived access token and a refresh token.
Response fields:
| Field | Type | Description |
|---|---|---|
| access_token | STRING | Short-lived access token (valid for 1 hour). |
| expires_in | INTEGER | Remaining lifetime of the access token in seconds. |
| token_type | STRING | Type of the returned token. Always Bearer. |
| session | STRING | User session identifier. |
| refresh_token | STRING | * Token that can be used to obtain a new access token. |
| id_token | STRING | * User identity token. |
- Note: the refresh token is only returned if your application set
access_typetoofflinein the initial request. - Note: the identity token (
id_token) is only returned if your application included one of the following values inscope:openid,profile, oremail.
Example request:
POST http://localhost:8080/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id=YOUR-CLIENT-ID&
client_secret=YOUR-CLIENT-SECRET&
grant_type=authorization_code&
code=b%2F8NpjbB4eLaukGr68tE7maTCeBISO%2FC7hWxKGuKb8I4Ysc7uw8a2MRUMWnO3Nzt&
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcode* Although not required by the specification, the authorization server also accepts requests in JSON format (Content-Type: application/json).
Example response:
{
"access_token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.[payload].[signature]",
"token_type" : "Bearer",
"expires_in" : 3600,
"session" : "dfe05b78a76b6ad8e0fcbef270671793b86aa848"
}The Implicit grant type is used by mobile and web applications (JavaScript applications running in a web browser) where the confidentiality of the client secret cannot be guaranteed. This grant type is also redirect-based; the access token is passed directly to the user agent for forwarding to the application. This makes the token available to the user and to other applications on the user's device. This grant type does not perform authentication of the application's identity; instead, it relies on the redirect URI registered with the authorization server.
- Identity tokens (
id_token) are not included in the redirect fragment. Refresh tokens (refresh_token) are included in the redirect only if returned by the database.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client (application) identifier. |
| redirect_uri | redirect_uri |
Required. The URI to which the authorization server will redirect the user agent (browser) along with the access token. |
| response_type | token | Required. JavaScript applications must set this parameter to token. This value instructs the authorization server to return the access token as a name=value pair in the URI fragment identifier (#) to which the user is redirected after the authorization process completes. |
| scope | scope |
Recommended. A space-separated list of scopes that define the resources your application can access on behalf of the user. |
| state | state |
Recommended. A set of random characters that will be returned by the server to the client (used to protect against replay attacks). |
Example request:
GET /oauth2/authorize?client_id=YOUR-CLIENT-ID&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&scope=api&response_type=token&state=c2FmZXR HTTP/1.1
Host: localhost:8080http://localhost:8080/oauth2/authorize?
client_id=YOUR-CLIENT-ID&
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Foauth2%2Fcallback&
response_type=token&
scope=api&
state=c2FmZXR
The access token or error message is returned in the hash fragment of the redirect URI:
Access token response:
http://localhost:8080/callback#token_type=Bearer&expires_in=3600&session=dfe05b78a76b6ad8e0fcbef270671793b86aa848&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.[payload].[signature]
-
In addition to
access_token, the fragment string also containstoken_type(alwaysBearer) andexpires_in(lifetime of the token in seconds). If thestateparameter was included in the access token request, its value is also included in the response. -
The redirect URI — in this case
http://localhost:8080/callback/index.html— must point to a web page that contains a script capable of extracting the access token from the redirect URI.
Error response:
http://localhost:8080/callback#code=403&error=access_denied&error_description=Access%20denied.
The authorization server supports a hybrid response mode. If both values code token (space-separated) are specified in the response_type parameter, the authorization server will return both an authorization code and an access token in a single response.
With this grant type, the user provides their credentials (username and password) directly to the application. The application then uses the received user credentials to obtain an access token from the authorization server. This grant type should only be used when no other option is available, and only when the application is fully trusted by the user (for example, when it is part of the service itself).
After the user provides their credentials to the application, the application requests an access token from the authorization server using a POST request.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client identifier. |
| client_secret | client_secret |
Required. The client secret. |
| grant_type | password | Required. As defined in the OAuth 2.0 specification, this field must contain the value password. |
| username | username |
Conditional. The user's login. Ignored if secret is provided. |
| password | password |
Conditional. The user's password. Ignored if secret is provided. |
| secret | secret |
Conditional. A secret code. If provided, the username and password fields are not required. |
| scope | scope |
Recommended. A space-separated list of scopes that define the resources your application can access on behalf of the user. |
- According to the OAuth 2.0 specification, the client authentication parameters (
client_idandclient_secret) may be passed either in the request body or in the HTTPAuthorizationheader (HTTP Basic authentication):
Authorization: Basic d2ViLXNlcnZpY2UucnU6Y2xpZW50IHNlY3JldA==
In response, the authorization server will return a JSON object containing a short-lived access token and a refresh token.
Response fields:
| Field | Type | Description |
|---|---|---|
| access_token | STRING | Short-lived access token (valid for 1 hour). |
| expires_in | INTEGER | Remaining lifetime of the access token in seconds. |
| token_type | STRING | Type of the returned token. Always Bearer. |
| session | STRING | User session identifier. |
| refresh_token | STRING | Token that can be used to obtain a new access token. |
| id_token | STRING | * User identity token. |
- Note: the identity token (
id_token) is only returned if your application included one of the following values inscope:openid,profile, oremail.
Example request:
POST http://localhost:8080/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id=YOUR-CLIENT-ID&
client_secret=YOUR-CLIENT-SECRET&
grant_type=password&
username=admin&
password=admin* Although not required by the specification, the authorization server also accepts requests in JSON format (Content-Type: application/json).
If both the client and user credentials are valid, the authorization server will return an access token for the application.
The Client Credentials grant type allows an application to access its own service account. This can be useful, for example, when an application wants to update its own registration information on the service or the redirect URIs, or to access other information stored in the application's service account via the API.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client identifier. |
| client_secret | client_secret |
Required. The client secret. |
| grant_type | client_credentials | Required. As defined in the OAuth 2.0 specification, this field must contain the value client_credentials. |
| scope | scope |
Recommended. A space-separated list of scopes that define the resources your application can access on behalf of the user. |
- According to the OAuth 2.0 specification, the client authentication parameters (
client_idandclient_secret) may be passed either in the request body or in the HTTPAuthorizationheader (HTTP Basic authentication):
Authorization: Basic d2ViLXNlcnZpY2UucnU6Y2xpZW50IHNlY3JldA==
In response, the authorization server will return a JSON object containing an access token and a refresh token.
Response fields:
| Field | Type | Description |
|---|---|---|
| access_token | STRING | Access token (valid for 1 day). |
| expires_in | INTEGER | Remaining lifetime of the access token in seconds. |
| token_type | STRING | Type of the returned token. Always Bearer. |
| session | STRING | User session identifier. |
| refresh_token | STRING | Token that can be used to obtain a new access token. |
| id_token | STRING | * User identity token. |
- Note: the identity token (
id_token) is only returned if your application included one of the following values inscope:openid,profile, oremail.
Example request:
POST http://localhost:8080/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id=YOUR-CLIENT-ID&
client_secret=YOUR-CLIENT-SECRET&
grant_type=client_credentialsAfter an access token expires, all API requests using it will return an error with code 403 ("Token expired"). If a refresh token (refresh_token) was issued alongside the access token, it can be used to obtain a new access token from the authorization server.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client identifier. |
| client_secret | client_secret |
Required. The client secret. |
| grant_type | refresh_token | Required. As defined in the OAuth 2.0 specification, this field must contain the value refresh_token. |
| refresh_token | refresh_token |
Required. The refresh token previously issued. |
| scope | scope |
Recommended. A space-separated list of scopes that define the resources your application can access on behalf of the user. |
- According to the OAuth 2.0 specification, the client authentication parameters (
client_idandclient_secret) may be passed either in the request body or in the HTTPAuthorizationheader (HTTP Basic authentication):
Authorization: Basic d2ViLXNlcnZpY2UucnU6Y2xpZW50IHNlY3JldA==
Example request:
POST http://localhost:8080/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id=YOUR-CLIENT-ID&
client_secret=YOUR-CLIENT-SECRET&
grant_type=refresh_token&
refresh_token=e%2FdtGmXCIzHvPMURn%2FTH9udTPxtKpR5FFifx2uvH1WqT4myXLtgyjkLgYDy7g3Ik5MrFRR82* Although not required by the specification, the authorization server also accepts requests in JSON format (Content-Type: application/json).
If the client credentials are valid, the authorization server will return a new short-lived access token and a new refresh token.
The Token Exchange grant type (RFC 8693) allows obtaining a new access token before the current one expires.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client identifier. |
| client_secret | client_secret |
Required. The client secret. |
| grant_type | urn:ietf:params:oauth:grant-type:token-exchange | Required. As defined in the specification, this field must contain the value urn:ietf:params:oauth:grant-type:token-exchange. |
| subject_token | subject_token |
Required. The previously issued token. |
| subject_token_type | subject_token_type |
Recommended. The type of the provided token. Available values: urn:ietf:params:oauth:token-type:jwt (default), urn:ietf:params:oauth:token-type:access_token, urn:ietf:params:oauth:token-type:refresh_token, urn:ietf:params:oauth:token-type:id_token. |
| scope | scope |
Recommended. A space-separated list of scopes that define the resources your application can access on behalf of the user. |
- According to the OAuth 2.0 specification, the client authentication parameters (
client_idandclient_secret) may be passed either in the request body or in the HTTPAuthorizationheader (HTTP Basic authentication):
Authorization: Basic d2ViLXNlcnZpY2UucnU6Y2xpZW50IHNlY3JldA==
Example request:
POST http://localhost:8080/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id=YOUR-CLIENT-ID&
client_secret=YOUR-CLIENT-SECRET&
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&
subject_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.[abbreviated for brevity].NorYsi-Ht826HUFCEArVZ60_dEUmYiJYXubnTyweIMg&
subject_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Ajwt* Although not required by the specification, the authorization server also accepts requests in JSON format (Content-Type: application/json).
If the client credentials are valid and the provided token has not expired, the authorization server will return a new short-lived access token and a new refresh token.
This grant type allows authentication using a JWT token issued by an external system (for example, Google).
The grant is disabled by default: the server answers 400 unsupported_grant_type without reaching the database, and logs the refusal at notice with the client address — at most one line a minute per worker process, with the number of refusals held back since the previous one. Enable it with "jwt_bearer": true in module.AuthServer together with jwt_bearer_clients — the client_ids allowed to use the grant (see Configuration); with the key on and no client listed, the grant stays off. When enabled, the client must authenticate with its own client_id and client_secret; the secret is never filled in from the Origin header, and the application of an external provider is not accepted as a client. The parameters must be sent in the request body, not in the URL. A missing or wrong client authentication is answered with 401 invalid_client (with WWW-Authenticate: Basic when the credentials came in the Authorization header). A client that has authenticated but is not in jwt_bearer_clients is answered with 400 unauthorized_client, and the refusal is logged at notice with the client_id and the client address, on the same terms (one line a minute per worker process, with the count held back); the list is consulted only after the client has authenticated. List only confidential clients — those that keep their secret on a server: the secret of an application shipped inside a mobile or browser application is known to anyone who has it, and its authentication proves nothing.
Request parameters:
| Field | Value | Description |
|---|---|---|
| client_id | client_id |
Required. The client identifier, unless sent in the Authorization header. |
| client_secret | client_secret |
Required. The client secret, unless sent in the Authorization header. |
| grant_type | urn:ietf:params:oauth:grant-type:jwt-bearer | Required. This field must contain the value urn:ietf:params:oauth:grant-type:jwt-bearer. |
| assertion | assertion |
Required. The JWT token issued by the external system. |
- According to the OAuth 2.0 specification, the client authentication parameters (
client_idandclient_secret) may be passed either in the request body or in the HTTPAuthorizationheader (HTTP Basic authentication):
Authorization: Basic d2ViLXNlcnZpY2UucnU6Y2xpZW50IHNlY3JldA==
Example request:
POST http://localhost:8080/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id=YOUR-CLIENT-ID&
client_secret=YOUR-CLIENT-SECRET&
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&
assertion=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.[abbreviated for brevity].NorYsi-Ht826HUFCEArVZ60_dEUmYiJYXubnTyweIMgAuthServer includes a ready-to-use Vue 3 + Vite single-page application for OAuth2 authentication flows. It lives in the frontend/ directory and provides:
- Login (
/login) — username/password and Google sign-in - Registration (
/register) — email verification with 6-digit code - Password recovery (
/recover) — email-based reset flow - OAuth2 consent (
/authorize) — authorization code grant consent screen - Error page (
/error) — user-friendly error display
- No tokens in JavaScript — authentication is cookie-based only (
HttpOnlycookies viacredentials: 'include'). NolocalStorage, no token management code. - Build-time configuration — all project-specific values (API host, client ID, branding) are injected via
VITE_*environment variables. No code changes needed between projects. - Internationalization — built-in i18n support (English + Russian). Add more locales by dropping JSON files into
src/i18n/. - Reusable across projects — the frontend is designed as a shared component of the AuthServer module. Each Apostol project builds its own instance with its own
.envand deploys it onauth.<domain>.
auth.example.com ← nginx serves frontend dist/
├─ /login ← Vue SPA (all routes → index.html)
├─ /register
├─ /recover
├─ /authorize
├─ /oauth2/* ← nginx proxies to Apostol backend
└─ /api/* ← nginx proxies to Apostol backend
The frontend is deployed as a same-origin proxy: nginx serves the static SPA and proxies /oauth2/ and /api/ requests to the Apostol backend. This avoids CORS issues entirely.
For full integration instructions, see
frontend/README.md.
{
"module": {
"AuthServer": {
"enable": true,
"jwt_bearer": false,
"jwt_bearer_clients": []
}
}
}Key (module.AuthServer.*) |
Default | Meaning |
|---|---|---|
jwt_bearer |
false |
Accept the JWT Bearer Grant on /oauth2/token, with client authentication, from the clients in jwt_bearer_clients. Read at worker start. |
jwt_bearer_clients |
[] |
The client_ids of the default provider allowed to use the JWT bearer grant, compared byte for byte with the client_id in oauth2/default.json. An array of strings, each taken as written (an element is not split, even one from "${VAR}"); or one string split on commas and blanks — the form a value from the environment takes ("${JWT_BEARER_CLIENTS}"). Absent, null, empty: the grant stays off even with jwt_bearer on. At worker start a warning is logged for an element that is not a non-empty string and for a value that is neither an array nor a string; with jwt_bearer on, also for every entry that is not the client_id of a non-external application of the default provider with a secret, and for no client listed; with jwt_bearer off the entries are not checked (an info line says so). Read at worker start; the check against oauth2/ is made then too. |
Follow the build and installation instructions for Apostol (C++20).
Footnotes
-
Apostol CRM — a template project built on the A-POST-OL (C++20) and PostgreSQL Framework for Backend Development frameworks. ↩