Skip to content
avin-langPublic

About

JSON Web Tokens for avin: HS256 signing and verification, claim checks, and bearer-auth middleware for avin.net.http

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jwt

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)

Tokens

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 aud written either way is read as the Vector of its names.
  • Only the claims that are set are written, in the order of the table.

Signing

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 that claims leaves unset, so one type can carry sub both ways; a claim set by both traps.

Verifying

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:

  1. The shape: three parts joined by .; a header that is base64url of a JSON object with a string alg; no crit header, 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.
  2. 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 of HS256 refuses an HS512 token even under the right key.
  3. The signature, compared in constant time, before anything of the payload is read.
  4. The registered claims' kinds: iss, sub and jti strings, aud a string or an array of strings, exp, nbf and iat numbers within what an Instant holds.
  5. The clock: the time clock answers must be before exp and not before nbf, each with leeway either way. With requireExpiry, the default, a token without exp is refused. iat is read and never checked.
  6. The issuer: where issuer is given, iss must equal it.
  7. The audience: where audience is given, aud must name it; where none is given, a token with an aud is 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

A program's own claims

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]))

Over HTTP

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 Authorization header, or one of another scheme: WWW-Authenticate: Bearer;
  • a Bearer header 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.

Tests

avin test in this directory runs the package's tests, in tests/; tests/readme.avin holds this page's examples.

About

JSON Web Tokens for avin: HS256 signing and verification, claim checks, and bearer-auth middleware for avin.net.http

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors