JSON Web Tokens for Avin: signing and verifying tokens with HMAC (HS256, HS512), the registered
claims checked against a clock with a leeway, a program's own claims through
json's derived decoders, a typed error for every way a token is
refused, and bearer authentication for the standard library's HTTP server.
The package's modules are dev.avinlang.jwt and dev.avinlang.jwt.http, written in Avin. A
program depends on it in its avin.hocon:
dependencies {
jwt { git = "github.com/avin-lang/jwt", version = "0.0.2" }
}It brings in json 0.0.4, which needs avin 0.0.41, and needs nothing else beyond the standard library.
import avin.time.{hours, now}
import dev.avinlang.jwt.{Claims, Signer, Verifier}
main()
val secret = "a secret of at least thirty-two bytes".bytes
val token = Signer(secret).sign(Claims(subject = Some("ada"), expires = Some(now() + hours(1))))
Verifier(secret).verify(token) match
Ok(t) -> println(t.claims.subject) // Some(ada)
Err(e) -> println(e)
A token is the compact form of RFC 7515: a header and a payload, each a JSON object written in
base64url without padding, joined by ., then . and the MAC of the two. The header a signer writes
is {"alg":"HS256","typ":"JWT"} (or HS512); the payload holds the claims.
data Claims(
issuer: Option[string] = None, iss
subject: Option[string] = None, sub
audience: Vector[string] = [], aud
expires: Option[Instant] = None, exp
notBefore: Option[Instant] = None, nbf
issuedAt: Option[Instant] = None, iat
id: Option[string] = None jti
)
- A time is an
Instant, written as whole seconds since 1970 (a fraction of a second is dropped) and read from any JSON number, a fraction kept to the microsecond. - An audience of one is written as a string, of several as an array, and none is left out; a
token's
audwritten either way is read as theVectorof its names. - Only the claims that are set are written, in the order of the table.
Signer(key, algorithm = HS256) makes tokens. The key is at least as long as the hash's output, 32
bytes for HS256 and 64 for HS512 (RFC 7518 § 3.2); a shorter one traps as the signer is made.
sign(claims)is a token of the registered claims.sign(claims, custom)adds the members a value of the program's own type encodes as, after the registered ones. The value must encode as an object. It may set a registered claim thatclaimsleaves unset, so one type can carrysubboth ways; a claim set by both traps.
Verifier(
key: Vector[byte],
algorithms: Vector[Algorithm] = [HS256],
issuer: Option[string] = None,
audience: Option[string] = None,
leeway: Duration = seconds(0),
requireExpiry: bool = true,
clock: () -> Instant = now
)
verify(text) answers the Token (its header, its claims and its whole payload as Json) or
the first thing wrong with it, a JwtError. It checks, in order:
- The shape: three parts joined by
.; a header that is base64url of a JSON object with a stringalg; nocritheader, since the verifier understands no extensions. A member written twice in the header or the payload is refused, so no other reader can take the other one. - The algorithm: it must be one of
algorithms.none, an algorithm the package does not know, and one the verifier was not given are all refused, before the signature is looked at, so a token cannot choose how it is checked: a verifier ofHS256refuses anHS512token even under the right key. - The signature, compared in constant time, before anything of the payload is read.
- The registered claims' kinds:
iss,subandjtistrings,auda string or an array of strings,exp,nbfandiatnumbers within what anInstantholds. - The clock: the time
clockanswers must be beforeexpand not beforenbf, each withleewayeither way. WithrequireExpiry, the default, a token withoutexpis refused.iatis read and never checked. - The issuer: where
issueris given,issmust equal it. - The audience: where
audienceis given,audmust name it; where none is given, a token with anaudis refused, since it is meant for someone else (RFC 7519 § 4.1.3).
import avin.time.{epochSeconds, seconds}
import dev.avinlang.jwt.{Claims, Expired, Signer, Verifier, WrongAudience}
main()
val secret = "a secret of at least thirty-two bytes".bytes
val token = Signer(secret).sign(Claims(audience = ["api"], expires = Some(epochSeconds(1000))))
val at = (n: long) -> Verifier(secret, audience = Some("api"), clock = () -> epochSeconds(n))
println(at(999).verify(token).isOk) // true
println(at(1000).verify(token).err == Some(Expired(epochSeconds(1000)))) // true
println(at(1000).verify(token).err) // Some(the token expired at 1970-01-01T00:16:40Z)
val late = Verifier(secret, audience = Some("api"), leeway = seconds(30), clock = () -> epochSeconds(1020))
println(late.verify(token).isOk) // true
val web = Verifier(secret, audience = Some("web"), clock = () -> epochSeconds(999))
println(web.verify(token).err is Some(WrongAudience(["api"]))) // true
Each refusal is its own variant of JwtError, with a message for a log that never holds the key:
| variant | the token |
|---|---|
Malformed(reason) |
is not three parts, or its header or payload is not the JSON object it must be |
BadBase64(segment, error) |
has a part that is not unpadded base64url |
BadJson(segment, error) |
has a header or payload that is not JSON, or a payload not of the type asked for |
BadSignature |
is not signed by the key |
UnsupportedAlgorithm(alg) |
names none, an unknown algorithm, or one the verifier was not given |
BadClaim(name) |
has a registered claim of the wrong kind |
MissingClaim(name) |
lacks exp, which the verifier requires |
Expired(expires) |
is past its exp |
NotYetValid(notBefore) |
is before its nbf |
WrongIssuer(found) |
is from another issuer, or names none |
WrongAudience(found) |
is for another audience, or for one where the verifier has none |
token.custom[C]() decodes the payload as a type with a JsonDecoder, and verifyAs[C](text) is
verify followed by it. A type derived with derives JsonDecoder reads the members its fields name
and passes over the rest, the registered claims among them; a payload that does not fit is
BadJson(Payload, error), the error naming the field.
import avin.time.{hours, now}
import dev.avinlang.json.{JsonDecoder, JsonEncoder, JsonKey}
import dev.avinlang.jwt.{Claims, Signer, Verifier}
data Session(sub: string, @JsonKey("https://example.com/roles") roles: Vector[string]) derives JsonEncoder, JsonDecoder
main()
val secret = "a secret of at least thirty-two bytes".bytes
val token = Signer(secret).sign(Claims(expires = Some(now() + hours(1))), Session("ada", ["admin"]))
println(Verifier(secret).verifyAs[Session](token)) // Ok(Session(ada, [admin]))
bearer(verifier, errors = plainError), in dev.avinlang.jwt.http, is a middleware for a route or
a group that runs the handler only for a request whose Authorization: Bearer <token> holds a token
the verifier accepts (RFC 6750). The scheme is matched in any case. Every other request is answered
401 with the page errors renders:
- no
Authorizationheader, or one of another scheme:WWW-Authenticate: Bearer; - a
Bearerheader whose token is missing, malformed or refused:WWW-Authenticate: Bearer error="invalid_token". Why it was refused is not told to the client.
The handler is given the request carrying the verified Token: request.value[Token]() is Some of
it behind bearer and None outside, and token.claims and token.custom[C]() read it as above.
import avin.net.http
import avin.net.http.{Response, Route, Router, ServerRequest}
import dev.avinlang.jwt.{Claims, Signer, Token, Verifier}
import dev.avinlang.jwt.http.bearer
// Greets the subject of the token `bearer` verified.
me(r: ServerRequest) -> Response = r.value[Token]() match
Some(t) -> Response.text(200, s"hello, ${t.claims.subject.get}")
None -> Response.text(500, "outside bearer")
main()
val secret = "a secret of at least thirty-two bytes".bytes
val router = Router(
[Route.get("/health", _ -> Response.text(200, "ok"))] ++ Route.group(
"/api",
[Route.get("/me", me)],
bearer(Verifier(secret, requireExpiry = false))
)
)
val server = http.serve("127.0.0.1", 0, router.handle).ok.get
val base = s"http://127.0.0.1:${server.port()}"
val none = http.get(base + "/api/me").ok.get
println(s"${none.status} ${none.header("WWW-Authenticate")}") // 401 Some(Bearer)
val token = Signer(secret).sign(Claims(subject = Some("ada")))
val inside = http.get(base + "/api/me", [("Authorization", "Bearer " + token)]).ok.get
println(inside.text) // hello, ada
server.shutdown()
Design decisions are recorded in docs/decisions.md.
avin test in this directory runs the package's tests, in tests/; tests/readme.avin holds this
page's examples.