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.
Exports
Section titled “Exports”enum Algorithm
Section titled “enum Algorithm”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
-
Hs256HMAC with SHA-256 under a shared secret.
-
Rs256RSA PKCS #1 v1.5 with SHA-256.
-
Ps256RSA PSS with SHA-256.
-
Es256ECDSA P-256 with SHA-256.
-
EdDsaEd25519.
Algorithm.to_string
Section titled “Algorithm.to_string”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.
Algorithm.inspect
Section titled “Algorithm.inspect”impl Debug for Algorithm
fn inspect(value: Algorithm) -> String
impl Debug.inspect
Algorithm.equal
Section titled “Algorithm.equal”impl Equatable for Algorithm
fn equal(a: Algorithm, b: Algorithm) -> Bool
impl Equatable.equal
struct SigningKey
Section titled “struct SigningKey”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>).
SigningKey.hs256
Section titled “SigningKey.hs256”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")
SigningKey.rs256
Section titled “SigningKey.rs256”fn rs256(key: PrivateKey) -> Result<SigningKey, String>
type function on SigningKey
An RS256 key, from an RSA private key.
SigningKey.ps256
Section titled “SigningKey.ps256”fn ps256(key: PrivateKey) -> Result<SigningKey, String>
type function on SigningKey
A PS256 key, from an RSA private key.
SigningKey.es256
Section titled “SigningKey.es256”fn es256(key: PrivateKey) -> Result<SigningKey, String>
type function on SigningKey
An ES256 key, from an ECDSA P-256 private key.
SigningKey.eddsa
Section titled “SigningKey.eddsa”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")
SigningKey.algorithm
Section titled “SigningKey.algorithm”fn algorithm(key: SigningKey) -> Algorithm
type function on SigningKey
The algorithm key signs with.
SigningKey.verifying_key
Section titled “SigningKey.verifying_key”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.
SigningKey.to_string
Section titled “SigningKey.to_string”impl Display for SigningKey
fn to_string(key: SigningKey) -> String
impl Display.to_string
SigningKey.inspect
Section titled “SigningKey.inspect”impl Debug for SigningKey
fn inspect(key: SigningKey) -> String
impl Debug.inspect
struct VerifyingKey
Section titled “struct VerifyingKey”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>).
VerifyingKey.hs256
Section titled “VerifyingKey.hs256”fn hs256(secret: Bytes) -> Result<VerifyingKey, String>
type function on VerifyingKey
An HS256 key: HMAC-SHA256 under secret, at least 32 bytes.
VerifyingKey.rs256
Section titled “VerifyingKey.rs256”fn rs256(key: PublicKey) -> Result<VerifyingKey, String>
type function on VerifyingKey
An RS256 key, from an RSA public key.
VerifyingKey.ps256
Section titled “VerifyingKey.ps256”fn ps256(key: PublicKey) -> Result<VerifyingKey, String>
type function on VerifyingKey
A PS256 key, from an RSA public key.
VerifyingKey.es256
Section titled “VerifyingKey.es256”fn es256(key: PublicKey) -> Result<VerifyingKey, String>
type function on VerifyingKey
An ES256 key, from an ECDSA P-256 public key.
VerifyingKey.eddsa
Section titled “VerifyingKey.eddsa”fn eddsa(key: PublicKey) -> Result<VerifyingKey, String>
type function on VerifyingKey
An EdDSA key, from an Ed25519 public key.
VerifyingKey.algorithm
Section titled “VerifyingKey.algorithm”fn algorithm(key: VerifyingKey) -> Algorithm
type function on VerifyingKey
The algorithm key checks.
VerifyingKey.to_string
Section titled “VerifyingKey.to_string”impl Display for VerifyingKey
fn to_string(key: VerifyingKey) -> String
impl Display.to_string
VerifyingKey.inspect
Section titled “VerifyingKey.inspect”impl Debug for VerifyingKey
fn inspect(key: VerifyingKey) -> String
impl Debug.inspect
struct Validation
Section titled “struct Validation”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.
Validation.inspect
Section titled “Validation.inspect”impl Debug for Validation
fn inspect(value: Validation) -> String
impl Debug.inspect
enum JwtError
Section titled “enum JwtError”enum JwtError Malformed String WrongAlgorithm String BadSignature Expired NotYetValid WrongIssuer WrongAudience MissingClaim String Claims String end
Why verify refused a token.
Variants
-
MalformedNot three base64url parts, or a header or claims that are not a JSON object.
-
WrongAlgorithmThe header’s
algis not the key’s algorithm, or isnone. -
BadSignatureThe signature is not the key’s over the header and claims.
-
Expiredexp, plus the leeway, has passed. -
NotYetValidnbf, less the leeway, has not come. -
WrongIssuerissis not theValidation’s issuer. -
WrongAudienceauddoes not name theValidation’s audience. -
MissingClaimA claim the
Validationrequires is missing. -
ClaimsThe claims are not the shape
verify_asreads them as, withJson.ShapeError’s message.
JwtError.to_string
Section titled “JwtError.to_string”impl Display for JwtError
fn to_string(e: JwtError) -> String
impl Display.to_string
JwtError.inspect
Section titled “JwtError.inspect”impl Debug for JwtError
fn inspect(value: JwtError) -> String
impl Debug.inspect
JwtError.equal
Section titled “JwtError.equal”impl Equatable for JwtError
fn equal(a: JwtError, b: JwtError) -> Bool
impl Equatable.equal
jwt.sign
Section titled “jwt.sign”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"))
jwt.sign_as
Section titled “jwt.sign_as”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.")
jwt.verify
Section titled “jwt.verify”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)
jwt.verify_as
Section titled “jwt.verify_as”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)