Authentication (JWT)
MARS uses JSON Web Tokens (JWT) for authentication. The flow is:
- The client posts credentials to a token resource.
- Your code validates them and sets the user name and roles.
- MARS signs a JWT and returns it (as a Bearer token and/or a cookie).
- The client sends that token on subsequent requests.
- The activation verifies the token and enforces authorization.
The token itself is represented by TMARSToken (MARS.Core.Token.pas).
The token resource
The quickest way to add login is to subclass TMARSTokenResource, which already implements the HTTP endpoints:
unit Server.Resources.Token;
interface
uses
MARS.Core.Attributes, MARS.Core.MediaType, MARS.Core.Token.Resource;
type
[Path('token')]
TTokenResource = class(TMARSTokenResource)
end;
implementation
uses MARS.Core.Registry;
initialization
MARSRegister(TTokenResource);
end.That base class gives you, under …/token:
| Verb | Method | Purpose |
|---|---|---|
GET | GetCurrent | Return the current token (to inspect validity / expiration). |
POST | DoLogin | Authenticate (form username + password) and issue a JWT. |
DELETE | Logout | Clear the token (and its cookie). |
DoLogin consumes application/x-www-form-urlencoded, so the client sends username=…&password=….
Implementing credential validation
Override Authenticate to check credentials and populate the identity. Set Token.UserName and Token.Roles; if you return True, MARS calls Token.Build with the application's JWT secret and returns the signed token.
type
[Path('token')]
TTokenResource = class(TMARSTokenResource)
protected
function Authenticate(const AUserName, APassword: string): Boolean; override;
end;
function TTokenResource.Authenticate(const AUserName, APassword: string): Boolean;
begin
Result := MyUserStore.CheckPassword(AUserName, APassword);
if Result then
begin
Token.UserName := AUserName;
if MyUserStore.IsAdmin(AUserName) then
Token.Roles := ['standard', 'admin']
else
Token.Roles := ['standard'];
end;
end;Optional hooks let you run logic around the process: BeforeLogin, AfterLogin, BeforeLogout, AfterLogout, and GetCredentials (override the latter to read credentials from somewhere other than the form, e.g. JSON or Basic auth).
Default demo behavior
The base TMARSTokenResource.Authenticate is a demo stub that accepts any user whose password equals the current hour. Always override it with real validation in production.
What Token.Build does
Token.Build(App.Parameters) writes the standard claims (iat, exp, iss) plus UserName and Roles, signs the payload with HMAC-SHA256 using the application's signing key (see Key rotation) and marks the token verified. Token.Build(secret) signs with an explicit secret instead. Duration and other settings come from the application parameters:
[DefaultApp]
JWT.Secret=<a long random value, MARSCmd generates one for new projects>
JWT.Issuer=MARS-Curiosity
JWT.Duration=1 ; days (also JWT.Duration.InMinutes / .InSeconds)
JWT.CookieEnabled=true
JWT.CookieName=access_token
JWT.CookieSecure=false
JWT.CookieSameSite=Lax ; Lax (default), Strict, None, UnspecifiedThe token cookie
With JWT.CookieEnabled (the default) the token is also sent as a cookie:
- HttpOnly: scripts in the page cannot read it, on every host (console, service, daemon, ISAPI, Apache, FastCGI, Indy or DCS).
- SameSite:
JWT.CookieSameSitecontrols it:
| Value | The browser sends the cookie... | Use it for |
|---|---|---|
Lax (default) | with requests from the same site and top-level navigations from other sites, not with cross-site POST or fetch | a web UI served by the same site as the API: a good protection against cross-site request forgery |
Strict | only with requests from the same site | the strictest choice, when users never follow links to the site from other sites while logged in |
None | with every request, cross-site ones included | a front end on another site that calls the API with credentials; MARS makes the cookie Secure too, as browsers require, so it travels on HTTPS only |
Unspecified | (attribute not written) the default of the browser | the behavior before MARS wrote SameSite |
On logout the cookie is deleted with the same attributes.
Your own cookies use the same options through IMARSResponse.SetCookie:
[Context] FResponse: IMARSResponse;
...
FResponse.SetCookie('theme', 'dark', '', '/', Now + 30, True {Secure}
, False {HttpOnly}, TMARSCookieSameSite.Lax);The shorter overload SetCookie(Name, Value, Domain, Path, Expiration, Secure) writes an HttpOnly cookie without SameSite.
The public default is never used silently
JWT_SECRET_PARAM_DEFAULT ships in the public source, so MARS does not fall back to it. When JWT.Secret is missing, or still equal to that default, TMARSToken.SecretFromParameters applies TMARSToken.DefaultSecretPolicy:
Generate(the default inDEBUGbuilds): a random secret is created once per process and used to sign and verify; tokens do not survive a restart.TMARSToken.GeneratedSecretInUsetells you it happened, and a debug message is emitted on Windows.Refuse(the default inRELEASEbuilds): the first operation that needs the secret raisesEMARSExceptionwith an explicit message.
The secret is required only where JWT is actually used: a request to a protected resource ([RolesAllowed], [Authenticated]), or the issuing of a token. An application whose resources are all public needs no JWT configuration at all, even in RELEASE builds; a token sent to such an application cannot be verified and is simply never trusted (IsVerified = False).
Set JWT.AllowDefaultSecret=true to knowingly keep the public default (never in production). Every reader of the secret, the token resource, the MCP OAuth server and the test helpers, goes through the same function. Projects created with MARSCmd get a random JWT.Secret in their .ini files.
Key rotation
A secret should not live forever: rotate it periodically, and immediately if it may have leaked. Replacing JWT.Secret alone invalidates every token already issued, logging everybody out. To rotate without that, give each key an id and keep the previous key around for verification only, until the tokens it signed have expired:
[DefaultApp]
; the active key: signs new tokens, its id goes in the "kid" header
JWT.KeyId=2026-10
JWT.Secret=<new long random value>
; retired keys: accepted only for tokens carrying that "kid"
JWT.PreviousSecret.2026-07=<the secret used until now>The kid (key id, RFC 7515) in the header of each token tells MARS which key signed it:
- a token with a
kidis checked only against the key with that id (the active one or aJWT.PreviousSecret.<kid>); an unknownkidmakes it invalid; - a token without a
kid, issued before key ids were configured, is checked againstJWT.Secret, then againstJWT.PreviousSecret(no suffix), if set.
A rotation, step by step:
- Generate a new secret and pick a new id (a date works well). Key ids use 1 to 64 characters among
A-Z a-z 0-9 . _ -. - Move the current secret to
JWT.PreviousSecret.<current id>(or toJWT.PreviousSecretif you were not using key ids yet), then setJWT.KeyIdandJWT.Secretto the new ones. - After one token lifetime (
JWT.Duration), remove the previous secret.
If the old secret leaked, skip the waiting: drop it right away and accept that its tokens stop working.
Several servers
Every server verifying the tokens must know the same keys. Update all of them before tokens signed with the new key reach them, for example by distributing the new key as JWT.PreviousSecret.<new id> first, then making it the active key everywhere.
Keys are read through TMARSToken.KeyProvider (IMARSTokenKeyProvider); the default TMARSParametersTokenKeyProvider implements the parameters above. Assign your own provider at startup to keep keys elsewhere, for example in a database or a secrets vault, or to rotate them automatically.
Asymmetric algorithms
By default tokens are signed with HS256: one shared secret (JWT.Secret) both signs and verifies, so every server that verifies tokens could also issue them. With an asymmetric algorithm a private key signs and a public key verifies: the servers that only check tokens hold the public key, and cannot forge one.
DefaultApp.JWT.Algorithm=ES256
DefaultApp.JWT.PrivateKey=keys\jwt-private.pem
DefaultApp.JWT.PublicKey=keys\jwt-public.pem| Parameter | Meaning |
|---|---|
JWT.Algorithm | HS256 (default), RS256, PS256 (RSA, 2048 bits or more) or ES256 (ECDSA, P-256 curve). |
JWT.PrivateKey | The key that signs new tokens. Only the server that issues tokens needs it. |
JWT.PublicKey | The key that verifies tokens. Every server that accepts them needs it. |
JWT.PreviousPublicKey.<kid>, JWT.PreviousPublicKey | Retired public keys, as JWT.PreviousSecret in Key rotation (JWT.KeyId names the active key). |
Each key is the name of a PEM file (relative to the folder of the executable; read once, restart the server to change it) or the PEM text itself, in one line with \n for the line breaks. The standard formats are read: PKCS#8 (BEGIN PRIVATE KEY), PKCS#1 and SEC1 private keys, BEGIN PUBLIC KEY public keys. With OpenSSL:
# ES256
openssl ecparam -name prime256v1 -genkey -noout -out jwt-private.pem
openssl ec -in jwt-private.pem -pubout -out jwt-public.pem
# RS256 or PS256
openssl genrsa -out jwt-private.pem 2048
openssl rsa -in jwt-private.pem -pubout -out jwt-public.pemThe algorithm comes from the configuration only: a token whose header declares another one is refused, whatever its signature (an HS256 token signed with the public key as the secret, for example). JWT.Secret is not used with an asymmetric algorithm. A server without JWT.PrivateKey verifies tokens and raises when asked to issue one; a protected resource of an application without JWT.PublicKey raises a configuration error.
Keep the private key out of the repository and readable only by the account of the server.
What each backend needs:
- mORMot (Windows): nothing else. RSA and ECDSA are part of the mORMot 2 units shipped with MARS, no DLL.
- JOSE: its default crypto providers rely on OpenSSL 1.0, which MARS never loads. Add the
MARS.JOSEJWT.TaurusTLSunit to theusesof the ignition, afterMARS.JOSEJWT.Token: it registers the providers based on TaurusTLS and OpenSSL 3. TaurusTLS is not shipped with MARS: put itsSourcefolder in the library path (or in the search path of the project), and deploylibcrypto-3.dllandlibssl-3.dll(libcrypto-3-x64.dllandlibssl-3-x64.dllfor Win64), both of them, where the executable finds them. Without that unit an asymmetricJWT.Algorithmraises an error that says so. When the OpenSSL 3 libraries are not found, the error names the files it needs. HS256 needs none of this.
The two backends read the same keys and verify each other's tokens.
Reading the identity in a resource
Inject TMARSToken with [Context] to read the authenticated user and claims:
[Path('me')]
TMeResource = class
private
[Context] Token: TMARSToken;
public
[GET]
function WhoAmI: string;
begin
if not Token.IsVerified then
raise EMARSAuthenticationException.Create('Not logged in', 403);
Result := Token.UserName + ' [' + string.Join(',', Token.Roles) + ']';
end;
end;Useful TMARSToken members:
| Member | Meaning |
|---|---|
Token | The raw JWT string. |
IsVerified | Passed signature verification. |
IsExpired | exp is in the past. |
UserName | The authenticated user. |
Roles | TArray<string> of granted roles. |
HasRole(role) | Membership test. |
Claims | All JWT claims as name/value pairs. |
Expiration, IssuedAt, Duration, DurationSecs | Lifetime info. |
KeyId | Id of the key that signed the token (kid header), empty when it has none. |
Build(App.Parameters) / Load(token, App.Parameters) | Issue / verify a token with the application's keys. |
Build(secret) / Load(token, secret) | Issue / verify a token with an explicit secret. |
Clear | Drop the token (and cookie). |
Bearer header vs cookie
MARS can carry the token two ways, both enabled by default when JWT.CookieEnabled=true:
- Authorization header —
Authorization: Bearer <jwt>. - Cookie — e.g.
access_token=<jwt>; MARS sets it on login and reads it on each request.
On the client, TMARSCustomClient.AuthEndorsement chooses between Cookie and AuthorizationBearer.
JWT backends
Two interchangeable signing backends are provided; pick one by adding the corresponding unit to your ignition uses:
- mORMot —
MARS.mORMotJWT.Token(common on Windows). - JOSE —
MARS.JOSEJWT.Token(used on Linux and where JOSE is preferred).
{$IFDEF MSWINDOWS}
, MARS.mORMotJWT.Token
{$ELSE}
, MARS.JOSEJWT.Token
{$ENDIF}Both produce standard tokens, HS256 by default or with an asymmetric algorithm, and accept only tokens of the configured algorithm (the alg in the token header never selects it); they differ in the underlying library.
The mORMot 2 units the backend needs ship with MARS (ThirdParty\mORMot2). The JOSE backend relies on the delphi-jose-jwt library: a git submodule of the MARS repository (ThirdParty\delphi-jose-jwt) and, with TMS Smart Setup, the paolo-rossi.delphi-jose-jwt product. The MARS.JOSE package requires its JOSE package.
Token renewal
To keep a session alive without a fresh login, re-Build the token when it is close to expiry. See the TokenRenew demo:
[Context] Token: TMARSToken;
[Context] App: IMARSApplication;
// ...
if Token.IsVerified then
begin
var LRemaining := Round(TTimeSpan.Subtract(Token.Expiration, Now).TotalSeconds);
if LRemaining < (Token.DurationSecs / 2) then
Token.Build(App.Parameters); // issue a fresh token (with the active key), resetting the clock
end;Next
- Authorization — gate endpoints by role with
[RolesAllowed]. - Client ▸ Authentication — logging in from a Delphi client with
TMARSClientToken.
