Skip to content

std::jwt

JSON Web Tokens (RFC 7519): a set of claims, such as who a user is and when the token expires, signed so that a server can check it was not changed. jwt.sign makes a token and jwt.verify checks one:

key = SigningKey.hs256(secret)?

token = jwt.sign({"sub" => Json.String("ada"), "exp" => Json.Int(expires)}, key)

claims = jwt.verify(token, SigningKey.verifying_key(key))?

Five algorithms: HS256 (HMAC-SHA256 with a shared secret), RS256 and PS256 (RSA), ES256 (ECDSA P-256) and EdDSA (Ed25519), over std::hash and std::signatures. A key is made for one algorithm, and verify refuses a token whose header names another: it never lets the token choose how it is checked, so an attacker cannot pass off a token signed with none, or signed with HMAC under an RSA public key. A token’s exp and nbf are checked against the clock with a minute’s leeway, and iss and aud against the Validation’s.

Claims are a JSON object, a Map<String, Json>, or a JsonObject that sign_as takes, such as a struct’s derived ToJson writes, checked by JsonObject.try_from; verify_as reads them as any type that derives FromJson.

There is no encryption (JWE), and no fetching of keys from a JWKS URL.

Import with import std::jwt.

enum Algorithm
    Hs256
    Rs256
    Ps256
    Es256
    EdDsa
end

A JWS algorithm, as RFC 7518 and RFC 8037 name it in a token’s alg.

Variants

  • Hs256

    HMAC with SHA-256 under a shared secret.

  • Rs256

    RSA PKCS #1 v1.5 with SHA-256.

  • Ps256

    RSA PSS with SHA-256.

  • Es256

    ECDSA P-256 with SHA-256.

  • EdDsa

    Ed25519.

impl Display for Algorithm

fn to_string(algorithm: Algorithm) -> String

impl Display.to_string

The algorithm’s alg name: HS256, RS256, PS256, ES256 or EdDSA.

impl Debug for Algorithm

fn inspect(value: Algorithm) -> String

impl Debug.inspect

impl Equatable for Algorithm

fn equal(a: Algorithm, b: Algorithm) -> Bool

impl Equatable.equal

struct SigningKey

opaque — construction surface is private to its defining module

A key that signs tokens with one algorithm. Its secret never prints: Display and Debug show SigningKey(<alg>).

fn hs256(secret: Bytes) -> Result<SigningKey, String>

type function on SigningKey

An HS256 key: HMAC-SHA256 under secret, which must hold at least 32 bytes, as RFC 7518 requires.

import std::jwt.SigningKey

assert SigningKey.hs256(String.to_bytes("short"))
    == Err("an HS256 secret needs at least 32 bytes, got 5")
fn rs256(key: PrivateKey) -> Result<SigningKey, String>

type function on SigningKey

An RS256 key, from an RSA private key.

fn ps256(key: PrivateKey) -> Result<SigningKey, String>

type function on SigningKey

A PS256 key, from an RSA private key.

fn es256(key: PrivateKey) -> Result<SigningKey, String>

type function on SigningKey

An ES256 key, from an ECDSA P-256 private key.

fn eddsa(key: PrivateKey) -> Result<SigningKey, String>

type function on SigningKey

An EdDSA key, from an Ed25519 private key.

import std::jwt.SigningKey
import std::signatures.PrivateKey

key = SigningKey.eddsa(PrivateKey.generate_ed25519())!
assert "${key}" == "SigningKey(EdDSA)"

assert SigningKey.eddsa(PrivateKey.generate_ecdsa_p256())
    == Err("EdDSA signs with an Ed25519 key, not ECDSA P-256")
fn algorithm(key: SigningKey) -> Algorithm

type function on SigningKey

The algorithm key signs with.

fn verifying_key(key: SigningKey) -> VerifyingKey

type function on SigningKey

The key that checks what key signs: the same secret for HS256, the public key for the others.

impl Display for SigningKey

fn to_string(key: SigningKey) -> String

impl Display.to_string

impl Debug for SigningKey

fn inspect(key: SigningKey) -> String

impl Debug.inspect

struct VerifyingKey

opaque — construction surface is private to its defining module

A key that checks tokens of one algorithm. Display and Debug show VerifyingKey(<alg>).

fn hs256(secret: Bytes) -> Result<VerifyingKey, String>

type function on VerifyingKey

An HS256 key: HMAC-SHA256 under secret, at least 32 bytes.

fn rs256(key: PublicKey) -> Result<VerifyingKey, String>

type function on VerifyingKey

An RS256 key, from an RSA public key.

fn ps256(key: PublicKey) -> Result<VerifyingKey, String>

type function on VerifyingKey

A PS256 key, from an RSA public key.

fn es256(key: PublicKey) -> Result<VerifyingKey, String>

type function on VerifyingKey

An ES256 key, from an ECDSA P-256 public key.

fn eddsa(key: PublicKey) -> Result<VerifyingKey, String>

type function on VerifyingKey

An EdDSA key, from an Ed25519 public key.

fn algorithm(key: VerifyingKey) -> Algorithm

type function on VerifyingKey

The algorithm key checks.

impl Display for VerifyingKey

fn to_string(key: VerifyingKey) -> String

impl Display.to_string

impl Debug for VerifyingKey

fn inspect(key: VerifyingKey) -> String

impl Debug.inspect

struct Validation
    leeway: Duration = Duration.seconds(60)
    issuer: Maybe<String> = None
    audience: Maybe<String> = None
    require_expiry: Bool = True
    now: Maybe<Instant> = None
end

What verify checks besides the signature.

impl Debug for Validation

fn inspect(value: Validation) -> String

impl Debug.inspect

enum JwtError
    Malformed String
    WrongAlgorithm String
    BadSignature
    Expired
    NotYetValid
    WrongIssuer
    WrongAudience
    MissingClaim String
    Claims String
end

Why verify refused a token.

Variants

  • Malformed

    Not three base64url parts, or a header or claims that are not a JSON object.

  • WrongAlgorithm

    The header’s alg is not the key’s algorithm, or is none.

  • BadSignature

    The signature is not the key’s over the header and claims.

  • Expired

    exp, plus the leeway, has passed.

  • NotYetValid

    nbf, less the leeway, has not come.

  • WrongIssuer

    iss is not the Validation’s issuer.

  • WrongAudience

    aud does not name the Validation’s audience.

  • MissingClaim

    A claim the Validation requires is missing.

  • Claims

    The claims are not the shape verify_as reads them as, with Json.ShapeError’s message.

impl Display for JwtError

fn to_string(e: JwtError) -> String

impl Display.to_string

impl Debug for JwtError

fn inspect(value: JwtError) -> String

impl Debug.inspect

impl Equatable for JwtError

fn equal(a: JwtError, b: JwtError) -> Bool

impl Equatable.equal

fn sign(claims: Map<String, Json>, key: SigningKey) -> String

A token holding claims, signed by key. Its header is {"alg":"<alg>","typ":"JWT"}.

import std::json.Json
import std::jwt.{self, SigningKey}

key = SigningKey.hs256(String.to_bytes("a secret of thirty-two bytes, or more"))!
token = jwt.sign({"sub" => Json.String("ada"), "admin" => Json.Bool(True)}, key)
assert String.starts_with(token, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.")

claims = jwt.verify(token, SigningKey.verifying_key(key), jwt.Validation{require_expiry: False})!
assert Map.get(claims, "sub") == Some(Json.String("ada"))
fn sign_as(claims: JsonObject, key: SigningKey) -> String

A token holding claims, a JsonObject, signed by key: a struct’s derived ToJson writes one, which JsonObject.try_from checks, so the claims are an object by their type, not by a check when the token is signed.

import std::json.{JsonObject, ToJson}
import std::jwt.{self, SigningKey}

key = SigningKey.hs256(String.to_bytes("a secret of thirty-two bytes, or more"))!
claims = JsonObject.try_from(ToJson.to_json({uid: 7}))!
token = jwt.sign_as(claims, key)
assert String.starts_with(token, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.")
fn verify(token: String, key: VerifyingKey, validation: Validation = Validation{}) -> Result<Map<String, Json>, JwtError>

The claims of token, once its signature is key’s and its header’s alg is key’s algorithm, and its exp, nbf, iss and aud pass validation. A header that names critical extensions (crit) is refused, since none is understood.

import std::base64
import std::instant.Instant
import std::json.Json
import std::jwt.{self, JwtError, Validation, VerifyingKey}

// RFC 7515, appendix A.1: an HS256 token for "joe" that expires at
// 1300819380.
secret = base64.decode_url(
    "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
)!

key = VerifyingKey.hs256(secret)!
token = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"

before = Validation{issuer: Some("joe"), now: Some(Instant.from_seconds(1_300_819_000))}
claims = jwt.verify(token, key, before)!
assert Map.get(claims, "http://example.com/is_root") == Some(Json.Bool(True))

after = Validation{now: Some(Instant.from_seconds(1_300_819_500))}
assert jwt.verify(token, key, after) == Err(JwtError.Expired)
assert jwt.verify(token, key, {..before, issuer: Some("ann")}) == Err(JwtError.WrongIssuer)
fn verify_as<T>(token: String, key: VerifyingKey, validation: Validation = Validation{}) -> Result<T, JwtError> where T: FromJson

The claims of token, checked as verify checks them, read as a T by its FromJson, such as a struct’s derived one.

import std::instant.Instant
import std::json.Json
import std::jwt.{self, SigningKey, Validation}

key = SigningKey.hs256(String.to_bytes("a secret of thirty-two bytes, or more"))!
token = jwt.sign({"uid" => Json.Int(7), "exp" => Json.Int(2_000_000_000)}, key)
now = Some(Instant.from_seconds(1_900_000_000))
claims: Map<String, Int> = jwt.verify_as(token, SigningKey.verifying_key(key), Validation{now:})!
assert Map.get(claims, "uid") == Some(7)