paolo-rossi/delphi-jose-jwt
Tentang
Implementasi JOSE (JSON Object Signing and Encryption) dan JWT (JSON Web Token) untuk Delphi.
Keamanan dan privasiPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- 0
- dalam 15 hari
- -1
- dalam 1 bulan
- Mengumpulkan riwayat
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliDelphi JOSE and JWT Library
What is Delphi JOSE and JWT Library
Delphi implementation of JWT (JSON Web Token) and the JOSE (JSON Object Signing and Encryption) specification suite. This library supports the JWS and JWE compact serializations with several JOSE algorithms (JWE: dir/RSA-OAEP/RSA-OAEP-256 with AES-GCM or AES-CBC-HMAC, "zip":"DEF" compression and nested JWTs included), plus full JWK (JSON Web Key) support and a swappable crypto provider backend (OpenSSL 1.0.x via Indy, OpenSSL 1.1.x/3.x/4.x via TaurusTLS, or pure-Pascal CryptoLib4Pascal).

:book: Documentation
The full documentation starts at Docs/index.md:
- Installation: Delphi versions, packages, deploying OpenSSL
- The JOSE standard: JWT, JWS, JWE, JWK and JWA explained, and where each lives in the library
- Guides: JWT (claims, producer, consumer) · JWS (signing and verifying) · JWE (encryption) · JWK (keys and key sets)
- Reference: Crypto providers · Security best practices · Troubleshooting
Every guide has a companion console project under Samples\ that compiles and runs all of its code.
:books: Articles about using Delphi-JOSE
- JWT authentication with Delphi. Part 1 - JWT and authentication technologies introduction (using Delphi)
- JWT authentication with Delphi. Part 2 - Understanding the JSON Web Token
- JWT authentication with Delphi. Part 3 - Using Delphi-JOSE-JWT to generate and verify JWT tokens
- JWT authentication with Delphi. Part 4 - Using JWT consumer to validate JWT's claims
:warning: Important: OpenSSL requirements
HMAC using SHA algorithm
Prior to Delphi 10 Seattle the the HMAC-SHA algorithm uses OpenSSL through the Indy library, so in order to generate the token you should have the OpenSSL DLLs in your server system.
In Delphi 10 Seattle or newer Delphi versions the HMAC algorithm is also in the System.Hash unit so OpenSSL is not needed.
RSA or ECDSA signatures
With the default provider stack, RSA (RS*/PS*) and ECDSA (ES*) signing and verification necessarily use OpenSSL, so if you plan to use these algorithms you have to download and deploy OpenSSL (on the server).
JWE (encryption)
With the default provider stack, every JWE algorithm goes through OpenSSL, dir included: JWE needs OpenSSL 1.0.2 or later (the RSA-OAEP digest controls arrived in 1.0.2, and they are what the version check uses). The JWE functions are loaded the first time JWE is used, so an OpenSSL library without them does not affect JWS. The CryptoLib stack needs no OpenSSL at all.
Client-side considerations
Please keep in mind that the client doesn't have to generate or verify the token (using SHA or RSA) so on the client-side there's no need for the OpenSSL DLLs.
OpenSSL download
If you need the OpenSSL library on the server, you can download the package directly to the Indy's GitHub project page (keep in mind to always update to the latest version and to match you application's bitness). With the default provider stack, pick the 1.0.2 binaries (libeay32.dll/ssleay32.dll): newer OpenSSL versions need the TaurusTLS-backed stack. On Linux, where distributions only ship OpenSSL 3.x, the default stack needs a separately installed OpenSSL 1.0.2 (libcrypto.so/libssl.so) on the library path
:satellite: Custom crypto providers (bring your own crypto)
Since PR #95, every crypto and Base64 operation goes through a swappable provider registry, TJOSEProviders (JOSE.Providers), instead of calling OpenSSL directly. Three provider stacks ship with the library:
| Provider stack | Unit | Backing library | Notes |
|---|---|---|---|
TJOSEDefaultProviders (default) |
JOSE.Providers.Default |
OpenSSL 1.0.x (1.0.2 recommended), via Indy | Registered automatically at startup. Needs the OpenSSL DLLs for RSA/ECDSA (see OpenSSL requirements above). The Indy that ships with Delphi refuses to load OpenSSL 1.1.0 or later ("Unable to load OpenSSL libraries"), and this stack also accesses a few raw OpenSSL struct fields that are opaque in 3.x/4.x — for OpenSSL 1.1.x/3.x/4.x use TJOSETaurusTLSProviders. Implements JWK PEM import/export and JWE (needs OpenSSL 1.0.2; loaded on first use, so an older library leaves JWS unaffected) |
TJOSETaurusTLSProviders |
JOSE.Providers.TaurusTLS |
OpenSSL 1.1.x/3.x/4.x, via the TaurusTLS binding for Indy | Only touches OpenSSL through accessor functions (RSA_get0_key/RSA_set0_key, EC_KEY_get0_public_key, EC_POINT_get/set_affine_coordinates, ...), so it's forward-compatible as OpenSSL's structs get more opaque. TaurusTLS itself already probes for -4 (OpenSSL 4.x) DLLs before falling back to -3/-1_1/-1. Implements JWK PEM import/export and JWE. Not part of the .dpk package contains list — get TaurusTLS from its repository, add its runtime package (or its Source folder) and JOSE.Providers.TaurusTLS.pas to your project manually, plus OpenSSL 3.x/4.x binaries (TaurusTLS links them from its OpenSSL distribution). The whole test suite runs on it through its own test project, Tests\JOSE.Tests.TaurusTLS.dproj |
TJOSECryptoLibProviders |
JOSE.Providers.CryptoLib |
pure-Pascal CryptoLib4Pascal | No native OpenSSL DLLs needed at all. Implements JWK PEM import/export and JWE. Not part of the .dpk package contains list — add JOSE.Providers.CryptoLib.pas and a CryptoLib4Pascal dependency (with its own dependencies, HashLib4Pascal and SimpleBaseLib4Pascal) to your project manually if you want it. The whole test suite runs on it through its own test project, Tests\JOSE.Tests.CryptoLib.dproj |
:warning: Unlike the default (OpenSSL/Indy) stack,
TJOSETaurusTLSProvidersandTJOSECryptoLibProvidersare not built into the JOSE.dpkpackages. Using either one in your own project means adding its unit(s) and backing library to your project manually (see the table above). Same story for the test suite:Tests\JOSE.Tests.TaurusTLS.dprojandTests\JOSE.Tests.CryptoLib.dprojare separate projects fromTests\JOSE.Tests.dprojprecisely because each pulls in its own extra, non-.dpkdependencies — see Running the tests below before trying to build them. More in the crypto providers guide.
Switching to the TaurusTLS-backed stack (OpenSSL 3.x/4.x) or the CryptoLib4Pascal-backed stack (and back):
uses
JOSE.Providers,
JOSE.Providers.TaurusTLS,
JOSE.Providers.CryptoLib;
begin
TJOSETaurusTLSProviders.Register; // OpenSSL 3.x/4.x capable, via TaurusTLS
...
TJOSECryptoLibProviders.Register; // from here on, no OpenSSL DLL is needed for HS/RS/ES signing
...
TJOSECryptoLibProviders.Unregister;
TJOSEProviders.RegisterProvider; // back to the OpenSSL 1.x-backed default
end;
To bring your own backend (a hardware security module, another crypto library, ...), implement whichever of the interfaces in JOSE.Providers.Interfaces you need and assign them directly — you don't have to replace the whole stack:
TJOSEProviders.RSA := TMyHSMBackedRSAProvider.Create;
TJOSEProviders.ECDSA := TMyHSMBackedECDSAProvider.Create;
| Interface | Capability |
|---|---|
IJOSEBase64Provider |
Base64 / Base64Url encode/decode |
IJOSEHmacProvider |
HMAC signing (HS256/384/512) |
IJOSESignerRSA |
RSA signing/verification (RS256/384/512, PS256/384/512) |
IJOSESignerECDSA |
ECDSA signing/verification (ES256/384/512/256K) |
IJOSECertificateProvider |
Public key extraction/verification from an X.509 certificate |
IJOSERSAKeyMaterialProvider |
Raw RSA key import/export to/from PEM (JWK support) |
IJOSEECKeyMaterialProvider |
Raw EC key import/export to/from PEM (JWK support) |
IJOSEAESGCMProvider |
AES-GCM (JWE content encryption: A128GCM/A192GCM/A256GCM) |
IJOSEAESCBCProvider |
AES-CBC with PKCS#7 padding (JWE content encryption: the AES half of A*CBC-HS*) |
IJOSERSAEncryptionProvider |
RSAES-OAEP (JWE key management: RSA-OAEP/RSA-OAEP-256) |
RSAKeyMaterial/ECKeyMaterial and the three JWE capabilities, AESGCM/AESCBC/RSAEncryption, are optional — a provider stack doesn't need to implement them unless you call TJSONWebKey.FromPEM/ToPEM (the two key-material ones) or use JWE (the three JWE ones). JWE key management does not need RSAKeyMaterial: RSA-OAEP asks the RSAEncryption provider for the key size. Every stack that ships with the library implements all five, but if you assign providers individually and leave them unset, ordinary signing and verification are unaffected; it just means those features will raise EJOSEProvidersNotRegistered until you supply an implementation.
:question: What is JOSE
JOSE is a standard that provides a general approach to the signing and encryption of any content. JOSE consists of several RFC:
- JWT (JSON Web Token) - describes representation of claims encoded in JSON
- JWS (JSON Web Signature) - describes producing and handling signed messages
- JWE (JSON Web Encryption) - describes producing and handling encrypted messages
- JWA (JSON Web Algorithms) - describes cryptographic algorithms used in JOSE
- JWK (JSON Web Key) - describes format and handling of cryptographic keys in JOSE
Anatomy of a compact token
A JWT travels as a JWS (signed: anyone can read the claims, only the key holder can produce them) or as a JWE (encrypted: only the key holder can read the claims). Each part is Base64URL-encoded and the parts are joined by dots:
JWS (3 parts) header . payload . signature
| | |
| | +-- HMAC / RSA / ECDSA signature of "header.payload"
| +------------- the claims (iss, sub, aud, exp, ...), readable by anyone
+---------------------- alg, typ, kid
JWE (5 parts) header . encrypted key . IV . ciphertext . tag
| | | | |
| | | | +-- authentication tag
| | | +------------ the encrypted claims (or a whole signed JWS)
| | +--------------------- random per token
| +--------------------------------- the content key encrypted with RSA-OAEP, empty for "dir"
+--------------------------------------------- alg, enc, zip, cty, kid (authenticated, not encrypted)
How the library fits together
flowchart LR
C["TJWT<br/>header + claims"] -->|"TJOSE.SerializeCompact<br/>TJOSEProcess"| JWS["JWS<br/>signed"]
C -->|"TJOSE.Encrypt"| JWE["JWE<br/>encrypted"]
C -->|"TJOSE.SignAndEncrypt"| NJ["Nested JWT<br/>signed, then encrypted"]
JWS & JWE & NJ -->|"compact string"| R{{"Receiver"}}
R -->|"TJOSEConsumer.Process<br/>recommended for incoming tokens"| V["Verified TJWT<br/>validated claims"]
R -->|"TJOSE.Verify / Decrypt /<br/>DecryptAndVerify"| V
Under the hood every algorithm goes through a registry and, from there, through a swappable crypto provider:
flowchart TB
App["Your application"]
subgraph API["High-level API"]
Builder["TJOSE<br/>JOSE.Core.Builder"]
Producer["TJOSEProducerBuilder<br/>JOSE.Producer"]
Consumer["TJOSEConsumerBuilder<br/>JOSE.Consumer"]
end
subgraph Model["Object model"]
JWTm["TJWT / TJWTClaims"]
JWSm["TJWS"]
JWEm["TJWE"]
JWKm["TJWK / TJSONWebKey / TJSONWebKeySet"]
end
Registry["Algorithm registry - JWA<br/>HS, RS, PS, ES - dir, RSA-OAEP - AES-GCM, AES-CBC-HMAC - DEF"]
Providers["TJOSEProviders<br/>JOSE.Providers"]
subgraph Stacks["Provider stacks"]
Def["Default<br/>OpenSSL 1.0.x via Indy"]
Taurus["TaurusTLS<br/>OpenSSL 1.1 / 3.x / 4.x"]
CL["CryptoLib4Pascal<br/>pure Pascal, no DLLs"]
Own["Your own<br/>HSM, other library"]
end
App --> API --> Model --> Registry --> Providers --> Stacks
JWKm -.->|"PEM import/export"| Providers
:zap: General Features
Token serialization
- One method call to serialize a token
Token deserialization
- One method call to validate and deserialize a compact token
Token & Claims validation (Consumer)
| Algorithms | Supported |
|---|---|
exp |
✔️ |
iat |
✔️ |
nbf |
✔️ |
aud |
✔️ |
iss |
✔️ |
jti |
✔️ |
sub |
✔️ |
Any other check (typ, custom claims) can be added as a custom validator, see the JWT guide.
Easy to use classes for compact token production
- Easy to use
TJOSEProducerandTJOSEProducerBuilder(aliasTJOSEProcess) classes to build a new compact token with many options
Easy to use classes for custom validation
- Easy to use
TJOSEConsumerandTJOSEConsumerBuilderclasses to validate token with a fine granularity - Easy to write custom validators!
Signing algorithms
| Algorithms | Supported |
|---|---|
None |
✔️ don't use it! 💀 |
HS256 |
✔️ |
HS384 |
✔️ |
HS512 |
✔️ |
RS256 |
✔️ updated! 🔥 |
RS384 |
✔️ updated! 🔥 |
RS512 |
✔️ updated! 🔥 |
ES256 |
✔️ new! 🌟 |
ES384 |
✔️ new! 🌟 |
ES512 |
✔️ new! 🌟 |
ES256K |
✔️ new! 🌟 |
PS256 |
✔️ new! 🌟 |
PS384 |
✔️ new! 🌟 |
PS512 |
✔️ new! 🌟 |
PS* is RSASSA-PSS (RFC 7518 §3.5): the same
RSA keys as RS*, with PSS padding — MGF1 over the same hash and a salt the size of the digest.
PSS signatures are randomised, so signing the same input twice gives different (equally valid)
signatures. All three provider stacks implement it; on the OpenSSL-backed stacks a build without
the PSS entry points reports that plainly instead of failing at load time.
Encryption algorithms (JWE)
Key management (alg) |
Supported |
|---|---|
dir |
✔️ new! 🌟 |
RSA-OAEP |
✔️ new! 🌟 |
RSA-OAEP-256 |
✔️ new! 🌟 |
A128KW/A192KW/A256KW |
planned |
ECDH-ES (+A*KW) |
planned |
RSA1_5 |
❌ by design: vulnerable to padding-oracle attacks (RFC 8725) |
Content encryption (enc) |
Supported |
|---|---|
A128GCM |
✔️ new! 🌟 |
A192GCM |
✔️ new! 🌟 |
A256GCM |
✔️ new! 🌟 |
A128CBC-HS256 |
✔️ new! 🌟 |
A192CBC-HS384 |
✔️ new! 🌟 |
A256CBC-HS512 |
✔️ new! 🌟 |
Compression (zip) |
Supported |
|---|---|
DEF |
✔️ new! 🌟 always accepted on decryption, used on encryption only when asked |
Compact serialization only, single recipient. See JWE support below.
Security notes
alg: none is rejected. TUnsecureNoneAlgorithm is not registered in the algorithm factory,
so a token claiming none fails to verify whatever the configuration — the first of the two issues
in Auth0's Critical vulnerabilities in JSON Web Token libraries.
Algorithm substitution — always call SetExpectedAlgorithms. That article's second issue needs
care from you. As RFC 7515 requires, TJWS.VerifySignature takes the algorithm from the token's own
header, and a TJWK is an opaque byte blob with no key-type metadata to cross-check it against. So
if you verify with an RSA or EC public key and leave the consumer's algorithm list at its
default — which permits every algorithm — an attacker can re-sign claims of their choosing as
HS256, using that public key (which they have too) as the HMAC secret. Narrow the list to what you
actually issue:
TJOSEConsumerBuilder.NewConsumer
.SetVerificationKey(LPublicKey)
.SetExpectedAlgorithms([TJOSEAlgorithmId.RS256]) // <-- do this
.SetExpectedIssuer(True, 'my-issuer')
.Build
.Process(LCompactToken);
As defence in depth the HS* algorithms refuse a key carrying PEM armour, so the classic
RS256 → HS256 swap fails even with a wide algorithm list. That is a backstop, not the control: it is
bypassed along with every other key check by SetSkipVerificationKeyValidation /
TJWS.SkipKeyValidation, and it cannot help when both the expected and the substituted algorithm
are asymmetric. The algorithm allowlist is what you rely on.
Threading model. Signing and verifying are safe to do from several threads at once: the
algorithm registry is built during unit initialization and only read afterwards, the lazy OpenSSL
entry-point loads are serialized, and consumers, producers and validators hold no shared state.
What is not safe is reconfiguring the library while those threads run — installing a provider
stack (TJOSEProviders/TJOSECryptoLibProviders/TJOSETaurusTLSProviders), registering your own
algorithm, or flipping TBase64.StrictURLDecoding. Those are startup operations: do them once,
before the workers start. Registration itself is serialized, so two stacks cannot end up
interleaved, but readers are deliberately lock-free and a swap mid-flight can hand a worker half of
each stack.
Token segments must be strict base64url. RFC 7515 allows only the A-Za-z0-9-_ alphabet, with
no padding, no whitespace and no line breaks, and TBase64 enforces that before any decoding
happens — the underlying decoders are lenient in ways that differ between provider stacks and Delphi
versions. Without the check, a decoder that drops stray characters gives one logical token many wire
forms that all verify, which quietly breaks any denylist, replay cache or fingerprint keyed on the
token text. If you must talk to an issuer that emits non-conforming tokens, TBase64.StrictURLDecoding := False turns the check off globally.
X.509 certificates are key containers, not trust anchors. TJWS.SetKeyFromCert and
TRSA/TECDSA.VerifyWithCertificate take the public key out of a PEM certificate and verify with
it. Nothing else about the certificate is examined — not the chain, not the validity dates, not
revocation, not key usage, not the subject. A token signed by the matching private key verifies just
as happily under an expired, self-signed or untrusted certificate. This is the usual choice for a
JWT library (the trust decision belongs to whatever gave you the certificate), but it does mean the
certificate buys you no trust on its own: validate or pin it yourself before handing it over. The
same goes for the JWK x5u/x5c/x5t members — TJSONWebKey carries and serializes them
verbatim, never fetches x5u, never parses the x5c chain, and takes key material only from the
JWK's own members.
Encryption is not authentication. A JWE encrypted with RSA-OAEP needs only the recipient's
public key, so anyone can produce one: on its own it says nothing about who made the token. Sign,
then encrypt (a nested JWT) when the recipient must know the
issuer; the consumer requires a signature by default for exactly this reason. Its JWE allowlists
(SetExpectedKeyManagementAlgorithms/SetExpectedEncryptionAlgorithms) start empty, so a
consumer accepts no encrypted token until you say which algorithms it should take, and a signing
alg can never pass for a JWE one. Every failure while decrypting reports the same JWE decryption failed, so the error tells an attacker nothing about which step failed.
:key: JSON Web Key (JWK) support
Full RFC 7517 JSON Web Key support, via TJSONWebKey/TJSONWebKeySet in JOSE.Core.JWK:
oct(symmetric),RSAandEC(P-256 / P-384 / P-521 / secp256k1) key types- JSON (de)serialization of the standard members (
kty,use,key_ops,alg,kid,x5u/x5c/x5t/x5t#S256) plus the type-specific key material - PEM import/export (
FromPEM/ToPEM), for both public and private keys - RFC 7638 JWK Thumbprint (
Thumbprint) TJSONWebKeySetfor JWKS documents (AddKey,FindByKid, JSON round-trip)- A bridge (
ToKeyPair/FromKeyPair) to the legacyTJWK/TKeyPairtypes, so aTJSONWebKeycan be handed straight toTJOSE.Sign/TJOSE.Verify/TJOSEProducer TJOSE.Verify/VerifyOrRaiseoverloads that take aTJSONWebKeyor a wholeTJSONWebKeySetdirectly:
// Picks the key whose kid matches the token header, and refuses a key whose
// own alg contradicts it. A token with no kid resolves only against a
// single-key set - guessing between several keys is not acceptable
LToken := TJOSE.VerifyOrRaise(LJWKS, LCompactToken);
PEM import/export is backed by the crypto provider currently registered — every stack in the table above supports it, so FromPEM/ToPEM works with or without OpenSSL.
:book: JWK Practical Guide — reading a JWKS, extracting keys, signing with a JWK and validating an incoming token against a key set, memory ownership rules. Its snippets are the runnable
Samples\JWKGuideconsole project.
Import a PEM key and sign a token with it
uses
System.IOUtils,
JOSE.Core.JWK,
JOSE.Core.JWT,
JOSE.Core.JWA,
JOSE.Core.Builder;
var
LKey: TJSONWebKey;
LKeyPair: TKeyPair;
LToken: TJWT;
LCompact: TJOSEBytes;
begin
LKey := TJSONWebKey.FromPEM(TFile.ReadAllBytes('rsa-private.pem'));
try
// Use the JWK Thumbprint as a stable key id
LKey.Kid := LKey.Thumbprint;
// Bridge to the legacy key model and sign a token with it
LKeyPair := LKey.ToKeyPair;
try
LToken := TJWT.Create;
try
LToken.Claims.Subject := 'Paolo Rossi';
LCompact := TJOSE.SerializeCompact(LKeyPair.PrivateKey, TJOSEAlgorithmId.RS256, LToken);
memoCompact.Lines.Add(LCompact);
finally
LToken.Free;
end;
finally
LKeyPair.Free;
end;
finally
LKey.Free;
end;
end;
Build a symmetric key and a JWKS document
var
LKey: TJSONWebKey;
LSet: TJSONWebKeySet;
begin
LKey := TJSONWebKey.CreateOct('my_very_long_and_safe_secret_key');
LKey.Kid := 'hmac-key-1'; // set members you need before AddKey - see note below
LSet := TJSONWebKeySet.Create;
try
LSet.AddKey(LKey); // the set now owns LKey
memoJWKS.Lines.Add(LSet.ToJSON);
finally
LSet.Free; // also frees LKey
end;
end;
Note: to publish a JWKS, strip the private material first:
TJSONWebKey.ToPublicJWKreturns the public half of an RSA or EC key (carryingkid/use/algacross), andTJSONWebKeySet.ToPublicJWKSetdoes the same for a whole set, skippingoctkeys — which have no public half.
:lock: JSON Web Encryption (JWE) support
RFC 7516 JSON Web Encryption, compact serialization, single recipient:
- Key management:
dir(a shared secret) andRSA-OAEP/RSA-OAEP-256(encrypted to an RSA public key, 2048 bits or more; an X.509 certificate is accepted as the key container) - Content encryption:
A128GCM/A192GCM/A256GCMandA128CBC-HS256/A192CBC-HS384/A256CBC-HS512(Keycloak's default isRSA-OAEP+A128CBC-HS256), with a fresh random IV for every token; the CBC-HMAC tag is checked before anything is decrypted - Compression (
"zip":"DEF"): compressed tokens are always decrypted, with a cap on the decompressed size (TJWE.MaxDecompressedSize); a token is compressed only when its header asks for it, since compressing before encrypting can leak secrets through the length (RFC 8725 §3.6) - Nested JWTs (signed, then encrypted,
"cty":"JWT"):TJOSE.SignAndEncrypt/TJOSE.DecryptAndVerify TJOSE.Encrypt/TJOSE.Decryptfor encrypted (not signed) claimsTJOSEConsumersupport, with separate decryption and verification keys and JWE algorithm allowlists- All three provider stacks, checked against the RFC 7516/7518/7520 test vectors
:book: JWE Practical Guide — choosing between signing, encrypting or both,
dirand RSA-OAEP, nested JWTs, validating encrypted tokens with the consumer, Keycloak-style tokens (AES-CBC-HMAC), compression, error handling, memory ownership rules. Its snippets are the runnableSamples\JWEGuideconsole project.
Sign, then encrypt (nested JWT)
uses
System.SysUtils, System.DateUtils, System.IOUtils,
JOSE.Core.JWA,
JOSE.Core.JWK,
JOSE.Core.JWT,
JOSE.Core.Builder,
JOSE.Consumer;
var
LSignKey, LEncryptKey: TJWK;
LToken: TJWT;
LCompactToken: string;
begin
LSignKey := TJWK.Create('my_very_long_and_safe_secret_key');
LEncryptKey := TJWK.Create(TFile.ReadAllBytes('recipient-public.pem'));
LToken := TJWT.Create;
try
LToken.Claims.Issuer := 'https://auth.example.com';
LToken.Claims.Subject := 'paolo.rossi';
LToken.Claims.Expiration := IncHour(Now, 1);
// HS256 signature, then RSA-OAEP-256 + A256GCM encryption
LCompactToken := TJOSE.SignAndEncrypt(LSignKey, TJOSEAlgorithmId.HS256,
LEncryptKey, TJOSEAlgorithmId.RSA_OAEP_256, TJOSEEncryptionAlgorithmId.A256GCM, LToken);
finally
LToken.Free;
LEncryptKey.Free;
LSignKey.Free;
end;
end;
Validate an encrypted token
TJOSEConsumerBuilder.NewConsumer
// One key per layer: decrypt the JWE, verify the JWS inside it
.SetDecryptionKey(TFile.ReadAllBytes('recipient-private.pem'))
.SetVerificationKey('my_very_long_and_safe_secret_key')
// JWE allowlists: empty by default, so no encrypted token gets in unless listed
.SetExpectedKeyManagementAlgorithms([TJOSEAlgorithmId.RSA_OAEP_256])
.SetExpectedEncryptionAlgorithms([TJOSEEncryptionAlgorithmId.A256GCM])
.SetExpectedAlgorithms([TJOSEAlgorithmId.HS256])
.SetExpectedIssuer(True, 'https://auth.example.com')
.SetRequireExpirationTime
.Build
.Process(LCompactToken);
TJOSE.Decrypt refuses a nested JWT and TJOSE.Verify refuses any JWE, so a signature check cannot
be skipped by calling the wrong function. Not supported yet: AES key wrap, ECDH-ES, the JSON
serializations, and JWE in TJOSEProducer.
:rocket: Projects using Delphi JOSE and JWT
| Project | Description | |
|---|---|---|
![]() |
WiRL | The RESTful library for Delphi, uses it for JWT-based authentication and authorization |
![]() |
TMS XData and TMS Sparkle | The TMS Software frameworks for REST/JSON services and HTTP servers, use it in their JWT authentication middleware. Read the blog post by Wagner R. Landgraf (he is also a contributor of this project) |
![]() |
MCPConnect | A framework to build MCP (Model Context Protocol) servers in Delphi, uses it for OAuth/token security |
![]() |
Horse | The Express-inspired web framework for Delphi and Lazarus, uses it through its horse-jwt middleware |
:cookie: Prerequisite
This library has been tested with Delphi 13 Florence, Delphi 12 Athens and Delphi 11 Alexandria (the whole test suite runs on all three). Runtime packages are provided for Delphi 10.1 Berlin and later (Packages\). With some work it should compile with **DXE6 and higher**, but I have not tried or tested this; if you succeed in this task I will be happy to create a branch of your work! Note that on XE6 and older Source\JOSE.inc switches off RSA_SIGNING, which compiles out RSA/ECDSA signing and the RSA-OAEP JWE key management: only HMAC, dir and the symmetric JWE algorithms remain.
Libraries/Units dependencies
This library has no required external dependencies when using the default (OpenSSL-backed) provider stack: everything it uses ships with Delphi. At runtime, RSA/ECDSA signing and JWE on that stack need the OpenSSL DLLs.
Delphi RTL units used:
- System.JSON (DXE6+): required, there is no fallback to the older Data.DBXJSON
- System.Rtti, System.TypInfo
- System.Generics.Collections, System.Generics.Defaults
- System.NetEncoding (DXE7+, used when available for Base64)
- System.Hash (Delphi 10 Seattle+: HMAC and the JWK thumbprint; older versions use Indy instead)
- System.ZLib (JWE compression,
"zip":"DEF") - System.Classes, System.SysUtils, System.StrUtils, System.DateUtils, System.IOUtils, System.Types
Indy units (the Indy that ships with Delphi is enough for the default stack):
- IdGlobal, IdCTypes, IdSSLOpenSSLHeaders: the OpenSSL bindings used for RSA/ECDSA signing, JWK PEM import/export and JWE
- IdHMAC, IdHMACSHA1, IdHashSHA, IdHash, IdSSLOpenSSL: only before Delphi 10 Seattle, for HMAC and the JWK thumbprint
Optional, only if you switch to another provider stack (neither is included in the .dpk package: add the libraries and the provider unit to your project yourself):
- TaurusTLS stack (
JOSE.Providers.TaurusTLS.pas): TaurusTLS and the OpenSSL 1.1.x/3.x/4.x DLLs - CryptoLib stack (
JOSE.Providers.CryptoLib.pas): CryptoLib4Pascal, with its dependencies HashLib4Pascal and SimpleBaseLib4Pascal; no OpenSSL DLL needed
Indy notes
- Please use always the latest version from GitHub
:test_tube: Running the tests
The DUnitX-based test suite has three projects, one per crypto stack. Each runs the whole suite, with every fixture that does not pin a stack of its own running on that project's stack, plus that stack's own provider tests:
| Project | Stack | Extra setup |
|---|---|---|
Tests\JOSE.Tests.dproj |
Default (OpenSSL 1.0.x via Indy) | None on Windows (the OpenSSL 1.0.2 DLLs are in Tests\Exe). On Linux, OpenSSL 1.0.2 must be on the library path (e.g. LD_LIBRARY_PATH) |
Tests\JOSE.Tests.TaurusTLS.dproj |
TJOSETaurusTLSProviders (OpenSSL 1.1.x/3.x/4.x) |
Expects the TaurusTLS sources in Libs\TaurusTLS, and OpenSSL 3.x/4.x DLLs discoverable at runtime |
Tests\JOSE.Tests.CryptoLib.dproj |
TJOSECryptoLibProviders (pure-Pascal) |
Expects CryptoLib4Pascal, HashLib4Pascal and SimpleBaseLib4Pascal in Libs\; run Libs\build-cryptolib-deps.ps1 once beforehand to precompile them into Libs\_build (their combined source tree is too deep for a single Delphi unit search path) |
Run the executables from Tests\Exe, since the key fixtures are found relative to the working directory. Each prints the provider stack it tests when it starts.
Each builds to its own console exe under Tests\Exe. From a Delphi command prompt (rsvars.bat run, or msbuild on PATH):
msbuild "Tests\JOSE.Tests.dproj" /p:Config=Debug /p:Platform=Win32
Tests\Exe\JOSE.Tests.exe
...and likewise for the other two .dproj files.
Since every project runs the whole suite on its own stack, every provider stack is held to the same tests and vectors, RFC 7516/7520 and Wycheproof included.
Project Wycheproof vectors
Tests\JOSE.Tests.dproj also runs the JOSE test vectors of Google's
Project Wycheproof (fixture TTestWycheproof, unit
Tests\Source\JOSE.Tests.Wycheproof.pas). These are JWS and JWE tokens produced by other
implementations, each marked valid or invalid, and most of them built to catch a known class of bug:
tampered RSA/PSS/ECDSA signatures, out-of-range ECDSA r/s, alg: none, algorithm and key
confusion, lenient base64url, keys with a forbidden use/key_ops, weak RSA keys, tampered JWE
headers, IVs, ciphertexts and tags.
The four vector files are kept unchanged in Tests\Data\Wycheproof, pinned to a Wycheproof commit
(see the README.md there, Apache-2.0 licensed). Each file is one test:
| Test | File | Run | Skipped |
|---|---|---|---|
JsonWebSignature |
json_web_signature_test.json |
401 | 0 |
JsonWebEncryption |
json_web_encryption_test.json |
21 | 118 |
JsonWebKey |
json_web_key_test.json |
26 | 0 |
JsonWebCrypto |
json_web_crypto_test.json |
55 | 28 |
- Skipped vectors use algorithms this library does not implement (AES key wrap, ECDH-ES,
RSA1_5). They are skipped rather than counted as rejected, which would pass every invalid one for the wrong reason. - Known deviations. The few vectors the library answers differently from Wycheproof are listed
in
KNOWN_DEVIATIONSin the unit, each with its reason: the library is stricter on purpose (STRICTER), the vector itself is wrong (VECTOR), or the case is flagged ambiguous by Wycheproof or is beyond what a JOSE library checks, such as ROCA-weak moduli (POLICY). A test fails when a new vector disagrees, and also when a listed one starts agreeing, so the list cannot go stale. - A rejection must come as one of the library's own exceptions: an access violation or a range or encoding error fails the vector even when the token ends up rejected.
- Wycheproof JWS payloads are opaque bytes rather than JWT claims, so the JWS vectors go through the
same steps as
TJOSE.Verifywith aTJSONWebKey(TJWSparsing, key selection,CheckPermits, key validation, signature check) minus the claims parse. JWE vectors go throughTJWE.DecryptPayloadunchanged. - They run on all three provider stacks, since each test project runs the whole suite.
To move to newer vectors, download the four files from a newer Wycheproof commit, update the commit
in Tests\Data\Wycheproof\README.md and run the fixture: its failure message lists every vector
whose outcome changed.
:floppy_disk: Installation
See the installation guide for runtime packages, DPM and deploying OpenSSL.
Manual installation
Simply add the source paths Source/Common and Source/JOSE to your Delphi project path and... you are good to go!
Boss package manager
Using the boss install command:
$ boss install github.com/paolo-rossi/delphi-jose-jwt
:scroll: Quick Code Examples
Creating a token
To create a token, simply create an instance of the TJWT class and set the properties (claims).
Using the fluent producer
The easiest way to build a JWT token (compact representation) is to use the IJOSEProducer interface (JOSE.Producer is not in the runtime package: add the unit to your project):
uses
JOSE.Core.JWA,
JOSE.Producer;
var
LResult: string;
begin
LResult := TJOSEProcess.New
.SetIssuer('Delphi JOSE Library')
.SetIssuedAt(Now)
.SetExpiration(Now + 1)
.SetAlgorithm(TJOSEAlgorithmId.HS256)
.SetKey('my_very_long_and_safe_secret_key')
.Build
.GetCompactToken
;
memoCompact.Lines.Add(LResult);
end;
Using TJOSE utility class
Another way to serialize, deserialize, verify a token is to use the TJOSEutility class:
uses
JOSE.Core.JWT,
JOSE.Core.Builder;
var
LToken: TJWT;
LCompactToken: string;
begin
LToken := TJWT.Create;
try
// Token claims
LToken.Claims.Issuer := 'WiRL REST Library';
LToken.Claims.Subject := 'Paolo Rossi';
LToken.Claims.Expiration := Now + 1;
// Signing and Compact format creation
LCompactToken := TJOSE.SHA256CompactToken('my_very_long_and_safe_secret_key', LToken);
mmoCompact.Lines.Add(LCompactToken);
finally
LToken.Free;
end;
Using TJWT, TJWS and TJWK classes
Using the TJWT, TJWS and TJWK classes you have more control over the creation of the final compact token.
var
LToken: TJWT;
LSigner: TJWS;
LKey: TJWK;
LAlg: TJOSEAlgorithmId;
begin
LToken := TJWT.Create;
try
// Set your claims
LToken.Claims.Subject := 'Paolo Rossi';
LToken.Claims.Issuer := 'Delphi JOSE Library';
LToken.Claims.IssuedAt := Now;
LToken.Claims.Expiration := Now + 1;
// Choose the signing algorithm
case cbbAlgorithm.ItemIndex of
0: LAlg := TJOSEAlgorithmId.HS256;
1: LAlg := TJOSEAlgorithmId.HS384;
2: LAlg := TJOSEAlgorithmId.HS512;
else LAlg := TJOSEAlgorithmId.HS256;
end;
// Create your key from any text or TBytes
LKey := TJWK.Create(edtSecret.Text);
try
// Create the signer
LSigner := TJWS.Create(LToken);
try
// With this option you can have keys < algorithm length
LSigner.SkipKeyValidation := True;
// Sign the token!
LSigner.Sign(LKey, LAlg);
memoCompact.Lines.Add('Header: ' + LSigner.Header);
memoCompact.Lines.Add('Payload: ' + LSigner.Payload);
memoCompact.Lines.Add('Signature: ' + LSigner.Signature);
memoCompact.Lines.Add('Compact Token: ' + LSigner.CompactToken);
finally
LSigner.Free;
end;
finally
LKey.Free;
end;
finally
LToken.Free;
end;
Unpack and verify a token's signature
Unpacking and verifying tokens is simple.
Using TJOSE utility class
You have to pass the key and the token compact format to the TJOSE.Verify class function
var
LKey: TJWK;
LToken: TJWT;
begin
// Create the key from a text or TBytes
LKey := TJWK.Create('my_very_long_and_safe_secret_key');
// Unpack and verify the token!
LToken := TJOSE.Verify(LKey, FCompactToken);
if Assigned(LToken) then
begin
try
if LToken.Verified then
mmoJSON.Lines.Add('Token signature is verified')
else
mmoJSON.Lines.Add('Token signature is not verified')
finally
LToken.Free;
end;
end;
end;
TJOSE.Verify raises EJOSEException for a malformed token (wrong number of parts, bad
base64url, a JWE), and returns nil when the header or payload is not readable JSON or the key is
refused (too short, wrong type). A token whose signature does not check out still comes back, with
Verified set to False, so that property must be tested.
When you would rather have a bad signature raise, use TJOSE.VerifyOrRaise — anything it returns
has verified:
LToken := TJOSE.VerifyOrRaise(LKey, FCompactToken); // raises EJOSEException otherwise
try
mmoJSON.Lines.Add(LToken.Claims.JSON.ToJSON);
finally
LToken.Free;
end;
Neither of them constrains the algorithm — both take it from the token's own header. For tokens
that come from outside, verify through TJOSEConsumer and set an algorithm allowlist.
Unpacking and token validation
Using the new class TJOSEConsumer it's very easy to validate the token's claims. The TJOSEConsumer object is built with the TJOSEConsumerBuilder utility class using the fluent interface.
What Process does with a token, in order (every check runs before the claims are trusted):
flowchart TD
T["Compact token"] --> P["Parse - TJOSEContext"]
P --> K{"JWS or JWE?"}
K -->|JWS| A1{"alg in<br/>SetExpectedAlgorithms?"}
A1 -->|yes| S1["Verify the signature<br/>SetVerificationKey"]
K -->|JWE| A2{"alg and enc in the JWE allowlists?<br/>empty by default"}
A2 -->|yes| D["Decrypt<br/>SetDecryptionKey"]
D -->|"nested JWT, cty: JWT"| A1
D -->|"plain JWE"| RS
S1 --> RS{"Signature present,<br/>or SetDisableRequireSignature?"}
RS -->|yes| VAL["Claim validators<br/>exp, nbf, iat, iss, aud, sub, jti, custom"]
VAL -->|all pass| OK(["Token accepted"])
A1 -->|no| X(["Rejected: exception"])
S1 -->|invalid| X
A2 -->|no| X
D -->|fails| X
RS -->|no| X
VAL -->|any fails| X
var
LConsumer: IJOSEConsumer;
begin
LConsumer := TJOSEConsumerBuilder.NewConsumer
.SetClaimsClass(TJWTClaims)
// JWS-related validation
.SetVerificationKey(edtConsumerSecret.Text)
.SetSkipVerificationKeyValidation
.SetDisableRequireSignature
// string-based claims validation
.SetExpectedSubject('paolo-rossi')
.SetExpectedAudience(True, ['Paolo'])
// Time-related claims validation
.SetRequireIssuedAt
.SetRequireExpirationTime
.SetEvaluationTime(IncSecond(FNow, 26))
.SetAllowedClockSkew(20, TJOSETimeUnit.Seconds)
.SetMaxFutureValidity(20, TJOSETimeUnit.Minutes)
// Build the consumer object
.Build();
try
// Process the token with your rules!
LConsumer.Process(Compact);
except
// (optionally) log the errors
on E: Exception do
memoLog.Lines.Add(E.Message);
end;
Time-related claims
exp,nbfandiatare compared as UTC epoch seconds (the RFC 7519 NumericDate), and the current time is read from the UTC clock, so validation isn't affected by the local time zone or by daylight saving time changes.- A non-integer NumericDate (
"exp":1700000000.5) is accepted and rounded down to the second. A date claim that is present but isn't a valid NumericDate ("nbf":"soon", a number outside the year 1–9999 range) makes the token invalid, even if that claim isn't required. SetEvaluationTimereplaces the clock with a fixed instant, which is useful for tests and replays. TheTDateTimeoverload takes a local time, which is ambiguous in the hour repeated when daylight saving time ends. For an exact instant, pass aTJOSENumericDate:
.SetEvaluationTime(TJOSENumericDate.FromSeconds(1792888200)) // epoch seconds
.SetEvaluationTime(TJOSENumericDate.FromUTC(LUtcDateTime)) // a UTC TDateTime
If you call SetEvaluationTime more than once, the last call wins.
Jelajahi proyek terkait
Memuat…



