Credentials and Sessions
A Moost server authenticates and authorizes its own users, with Aooth or any other Moost auth. Its connection to the OData service is an integration with a technical user: the service never sees the end users, and the server never passes on the Authorization header or the cookies of an incoming request. The space's init holds those credentials, and the space keeps the sessions with the service by itself.
import { createODataSpace } from "@atscript/db-odata";
import { basicAuth, callTimeout, combineAuth } from "@atscript/moost-odata";
import * as sales from "../src/odata/sales.as";
import { model } from "../src/odata/sales.model.gen";
const space = createODataSpace({
baseUrl: "https://my-gateway.example.com/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
query: { "sap-client": "100" },
model,
types: sales,
init: combineAuth(
basicAuth({ user: process.env.ODATA_USER!, password: process.env.ODATA_PASSWORD! }),
callTimeout(15_000),
),
});init is called once per table operation, inside the HTTP request it serves, and by space.connect() for the $metadata read at start, outside any request. The reads a write makes (its ETag read, the CSRF token fetch) and the write itself all carry what init returned.
Who may read or write what is your server's decision, made before a table is called: guards, scopes and the hooks of Moost Server. The technical user needs the rights of everything the server serves.
In the browser there is nothing to configure: the browser's own cookies and login are the credentials (see Browser Client).
Strategies
| Strategy | Sends |
|---|---|
basicAuth({ user, password }) | Authorization: Basic … |
bearerAuth(token) | Authorization: Bearer … with a fixed token |
bearerAuth((request) => token) | Authorization: Bearer … with the token the function returns, each time |
staticHeaders({ … }) | fixed headers: a credential in a header of its own, such as an API key |
callTimeout(ms) | an abort signal limiting one table operation, all its requests together |
combineAuth(a, b, …) | all of them merged; a later header or session replaces an earlier one |
| a function of your own | whatever it returns |
Each is an ODataAuth: a function that returns the options of the call (headers, signal, …). Signatures are in the API reference.
A token that expires
A function given to bearerAuth is asked for a token at every table operation. Cache the token there and fetch a new one before it expires, for example an OAuth client-credentials token:
import { bearerAuth } from "@atscript/moost-odata";
let token: { value: string; expiresAt: number } | undefined;
const auth = bearerAuth(async () => {
if (!token || token.expiresAt < Date.now() + 60_000) token = await fetchClientCredentialsToken();
return token.value;
});fetchClientCredentialsToken stands for your own call to the identity provider. The function runs in the request it is asked for and receives it, so a server that serves several tenants can pick the tenant's token.
A function of your own
A function is accepted wherever a strategy is. currentIncomingRequest() gives it the request it runs in, and Wooks composables work there too:
import { currentIncomingRequest, type ODataAuth } from "@atscript/moost-odata";
const auth: ODataAuth = async () => {
const tenant = currentIncomingRequest().header("x-tenant") ?? "default";
return { headers: { Authorization: `Bearer ${await tokenOfTenant(tenant)}` } };
};Outside an HTTP request (the read at start, a job, a script) the request has no headers. An error the function throws reaches the caller unchanged; throw an HttpError to choose the answer.
header(name) and cookie(name) read the request with Wooks' useHeaders and useCookies, so a cookie reads as Wooks reads it: the name is matched in any case, the Cookie header is split only at "; " (a pair after a bare ; is not found), an empty value is undefined, and a quoted value keeps its quotes; percent-encoding is undone.
Sessions
The space keeps a session with the service for each credential its calls send: the cookies the service sets and the CSRF token a write needs, which an SAP® service binds to its session cookie. Nothing to configure.
- One per credential. The session is chosen by the SHA-256 of the call's headers,
Accept-Languageleft out. With one technical user it is simply one session; a rotated token starts a new one. Two credentials never share a session or a CSRF token. - Bounded and expiring. A session is dropped after
ttlwithout use, and the one unused the longest whenmaxis reached. A dropped session is no error: the next call starts a new one. - Calls without credentials stay stateless: cookies the service sets are dropped, nothing is kept between calls.
const space = createODataSpace({
// …
sessions: { ttl: 20 * 60_000, max: 100 },
});| Option | Meaning | Default |
|---|---|---|
sessions.ttl | Milliseconds a session is kept after its last use; keep it at or below the service's own idle timeout | 30 minutes (DEFAULT_SESSION_TTL) |
sessions.max | The most sessions kept at once | 1000 (DEFAULT_MAX_SESSIONS) |
sessions: false | No sessions: every call stateless |
A write needs a session: without one (no credentials, or sessions: false) an SAP service refuses it, answered 502 STORE_FAILED, with the remedy in the server's log. A session also spares the service a new logon with every call. See Writes and Concurrency.
Refused credentials
A refusal of the server's credentials is the server's fault, never the caller's: the caller cannot sign in again to fix it.
| The service | Answer |
|---|---|
401 or 403 | 502 STORE_FAILED |
| an HTML login page in place of data, or a redirect answering a write (never followed) | 502 STORE_FAILED |
At start, a refused $metadata read rejects space.connect(), and the app does not start. Every answer of the mapping is in Errors.
DOs and DON'Ts
- Authenticate and authorize your users in the server — don't expect the service to tell them apart.
- Give the space one technical user with the rights of everything it serves — the same credentials read the
$metadataat start. - Cache a token that expires in the
bearerAuthfunction — it is asked at every table operation. - Keep the credentials on the server, in environment variables or a secret store — never in the browser bundle.
- Leave
sessionson whenever the server writes — withsessions: falsea write to an SAP service fails.
See also
@atscript/moost-odataAPI: the strategies,currentIncomingRequest.@atscript/db-odataAPI:sessions,DEFAULT_SESSION_TTL,DEFAULT_MAX_SESSIONS.- Writes and Concurrency: CSRF and sessions from the write side.
- Errors: how refusals are answered.