package jws

  1. Overview
  2. Docs

Module JwtSource

JWT - JSON Web Token (RFC 7519)

A thin layer on top of Jws Compact Serialization that interprets the payload as a JSON claims set.

Encoding a JWT

  let claims =
    Jwt.Claims.empty
    |> Jwt.Claims.sub "1234567890"
    |> Jwt.Claims.iss "https://example.com"
    |> Jwt.Claims.iat 1516239022.
    |> Jwt.Claims.add "admin" Jsont.bool true
  in
  let token = Jwt.encode pk claims

Decoding and validating a JWT

  let now = Unix.gettimeofday () in
  match Jwt.decode ~now ~aud:"https://api.example.com" ~public token with
  | Ok jwt ->
      let sub = Jwt.sub jwt in
      let admin = Jwt.claim jwt ~key:"admin" Jsont.bool in
      ...
  | Error (`Msg e) -> ...

Claims

Claims are built as Jsont.json string maps, the same representation used for protected header members in Jws. The Claims module provides helpers for the registered claim names defined by RFC 7519, 4.1.

Sourcemodule Claims : sig ... end

Decoded JWT values

Sourcetype t

A decoded and verified JWT.

Sourceval jws : t -> Jws.t

header jwt is the underlying JWS value. Use Jws.value to read header fields such as "kid".

Sourceval sub : t -> string option

sub jwt is the "sub" claim.

Sourceval iss : t -> string option

iss jwt is the "iss" claim.

Sourceval aud : t -> string list option

aud jwt is the "aud" claim, normalized to a list (a single-string audience is returned as a singleton list).

Sourceval exp : t -> float option

exp jwt is the "exp" claim.

Sourceval nbf : t -> float option

nbf jwt is the "nbf" claim.

Sourceval iat : t -> float option

iat jwt is the "iat" claim.

Sourceval jti : t -> string option

jti jwt is the "jti" claim.

Sourceval value : t -> key:string -> 'a Jsont.t -> 'a option

value jwt ~key codec reads a custom claim via a Jsont.t codec. Returns None when the claim is absent or cannot be decoded.

Encoding

Sourceval encode : ?kid:string -> ?extra:Jsont.json Jws.S.t -> Jws.Pk.t -> Claims.t -> string

encode pk claims produces a signed JWT in Compact Serialization. The algorithm is derived from pk and a "typ":"JWT" header is added.

Decoding

Sourceval decode : ?now:float -> ?aud:string -> ?public:Jws.Jwk.t -> string -> (t, [> `Msg of string ]) result

decode ?now ?aud ?public token decodes and verifies a JWT.

  • If now is provided, the "exp" and "nbf" claims are validated against it. If now is omitted, time-based validation is skipped.
  • If aud is provided, the "aud" claim must be present and contain aud.
  • public is the verification key (see Jws.Compact.decode).