santoku-jwt
View on LuaRocksJSON Web Tokens over a pluggable crypto backend, with claim checks and cached remote JWKS
santoku-jwt signs, parses and verifies JSON Web Tokens, checks their claims, and builds and caches JWKS documents. The core is plain Lua and takes a crypto backend: require("santoku.jwt")(backend).
Details
- The core takes a crypto backend the way santoku-http takes a socket backend.
- santoku.jwt.monocypher signs and verifies ES256 natively, in WebAssembly and under OpenResty. So the examples on this page run in your browser.
- santoku-resty's santoku.resty.jwt.openssl signs and verifies ES256 and RS256 inside an nginx worker.
- Private keys are JWKs, so a key made by one backend works in the other.
Keys, signing and verifying
keypair(alg) returns a private JWK and its public JWK. sign(claims, private) returns a compact token. verify(token, get_jwk[, opts]) returns true and { header, payload }, or false and a reason.
local utc = require("santoku.utc")
local jwt = require("santoku.jwt")(require("santoku.jwt.monocypher"))
local private, jwk = jwt.keypair()
print("kid:", jwk.kid, "has d:", jwk.d ~= nil)
local token = jwt.sign({ sub = "u1", aud = "app", exp = utc.time() + 3600 }, private)
local ok, data = jwt.verify(token, jwt.keyset(jwt.jwks(jwk)))
print("verified:", ok, "sub:", data.payload.sub, "alg:", data.header.alg)
print("public:", jwt.public(private).kid == jwk.kid, jwt.thumbprint(jwk) == jwk.kid, jwt.algs[1])
return ok
Details
- keypair's alg defaults to ES256.
- The public JWK carries kty, crv, x, y, alg, use sig, and the RFC 7638 thumbprint as kid.
- The token's header names the private key's alg and kid.
- jwks(jwk, ...) wraps public JWKs into the { keys } document you serve.
- keyset(doc) turns that document into the kid lookup that verify takes.
- public(private) rebuilds the public JWK from a private JWK.
- thumbprint(jwk) computes the RFC 7638 kid.
- algs lists the backend's algorithms.
- Keep the private JWK out of the repo, because its d member is the secret.
Claims and rejections
Without opts.claims, verify checks claims({ time = opts.time }). exp must be a number after the current time, and a present nbf must not be after it, with no leeway.
local utc = require("santoku.utc")
local jwt = require("santoku.jwt")(require("santoku.jwt.monocypher"))
local private, jwk = jwt.keypair()
local keys = jwt.keyset(jwt.jwks(jwk))
local now = utc.time()
local spec = jwt.claims({ aud = "app", iss = "https://auth.example", leeway = 30 })
local good = jwt.sign({ aud = "app", iss = "https://auth.example", exp = now + 60 }, private)
print("good:", jwt.verify(good, keys, { claims = spec }))
print("other aud:", jwt.verify(jwt.sign({ aud = "x", iss = "https://auth.example", exp = now + 60 }, private), keys, { claims = spec }))
print("expired:", jwt.verify(jwt.sign({ exp = now - 1 }, private), keys))
print("rs256 only:", jwt.verify(good, keys, { algs = { "RS256" } }))
return select(2, jwt.verify("not.a.token", keys))
Details
- claims({ aud, iss, leeway, time }) builds a claim spec. Pass it as opts.claims.
- That spec also checks aud, as a string or an array that contains it, and iss. It allows leeway seconds of clock skew.
- opts.time replaces the backend's clock only in the default spec, since a spec from claims() takes its own time.
- opts.algs narrows the accepted algorithms.
- A failed claim check returns false, its message and the claim's name. The messages are expired, wrong audience, wrong issuer and not yet valid.
- Before the claims, verify rejects a token with one of the reasons in the table.
| Reason | Followed by |
|---|---|
| Malformed token | |
| Unsupported alg, including none and every HMAC alg | the alg |
| No kid | |
| No jwk for kid | the kid |
| Unsupported key type | the kty |
| Key alg mismatch | the key's alg |
| Bad signature |
Parse without verifying
parse(token) splits a token without verifying it. It returns header, payload, signing_input and the raw signature, or nil and Malformed token. A backend's verify(alg, jwk, signing_input, signature) checks one signature directly.
local backend = require("santoku.jwt.monocypher")
local jwt = require("santoku.jwt")(backend)
local obj = jwt.parse("eyJhbGciOiJFUzI1NiJ9"
.. ".eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
.. ".DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q")
print("iss:", obj.payload.iss, "exp:", obj.payload.exp)
return backend.verify("ES256", {
kty = "EC", crv = "P-256",
x = "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
y = "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0",
}, obj.signing_input, obj.signature)
Details
- The token and key below are RFC 7515's ES256 example, from appendix A.3.
- That example's header has no kid, so jwt.verify itself would answer No kid.
A remote JWKS
remote_jwks(url, opts) returns a kid lookup backed by a fetched JWKS. Pass opts.client, any santoku-http client, or opts.fetch(url), which returns status and body, and opts.runtime. Create the lookup once and reuse it, or every call starts with an empty cache.
local http = require("santoku.http")(require("santoku.socket"))
local jwt = require("santoku.jwt")(require("santoku.jwt.monocypher"))
local certs = jwt.remote_jwks("https://auth.example/.well-known/jwks.json", {
client = http,
runtime = require("santoku.system.async"),
})
local ok, data = jwt.verify(token, certs, { claims = jwt.claims({ aud = "app" }) })
print(ok, ok and data.payload.sub or data)
Details
- opts.runtime: santoku.web.async, santoku.resty.async or santoku.system.async. remote_jwks raises without it. santoku.resty.jwt passes santoku.resty.async.
- opts.ttl: the lookup refetches after this many seconds. The default is 3600.
- opts.min_interval: on an unknown kid, the lookup refetches at most once per this many seconds. The default is 60.
- opts.wait: callers that arrive while a fetch is in flight wait on a semaphore from opts.runtime for up to this many seconds. The default is 10.
- The lookup keeps the last good set when a fetch fails or returns a document without a keys array.
Backends
A backend is a table of algs, sign, verify, keypair and now. algs lists what the backend handles, and the core refuses any other alg before it calls the backend.
local jwt = require("santoku.jwt")(require("santoku.resty.jwt.openssl"))
local private, jwk = jwt.keypair("RS256")
local token = jwt.sign({ sub = "u1", exp = ngx.time() + 3600 }, private)
ngx.say(jwt.verify(token, jwt.keyset(jwt.jwks(jwk))))
Details
- sign(alg, private, data) returns the raw signature. For ES256 that's the 64-byte r and s that JWS uses.
- verify(alg, jwk, data, sig) returns a boolean.
- keypair(alg, opts) returns a private JWK.
- now() returns epoch seconds.
- santoku.resty.jwt.openssl implements ES256 and RS256 on the OpenSSL linked into nginx.
- Its keypair("RS256", { bits }) defaults to 2048 bits.