Standard library · Security and cryptography

jwt

Making and checking JWT tokens, and guarding API routes.

import jwt

A JWT is a token the server signs after a user logs in and the client sends with every request; by checking the signature the server knows who the user is without going to the database. This package signs and checks tokens with the HMAC algorithms HS256, HS384 and HS512, never accepts the none algorithm, and has helpers for net.http handlers. Every service that checks a token needs the same secret, so it suits one backend or a few services you trust; there are no RS256 or ES256 public key signatures. When the client is a browser on your own site, a server side net.http.session is often simpler and can be revoked at once.

For an API, make a Guard with the secret and call Require or one of its siblings at the top of every handler; when the token is missing or wrong, the 401 or 403 answer is sent for you. The secret has to be long and random, for instance from RandomToken in crypto.

Things that catch people out:

  • A token without exp is accepted forever unless you set opts.require_exp. Tokens from Issue always have one, but a token signed some other way may not.
  • The secret is not checked for strength. Any non-empty string is used as it is; a short one can be guessed offline from a single token.
  • The claims are signed, not encrypted. Anyone holding a token can read them with a base64 decoder, so put no secrets in them.
  • A token cannot be taken back before it expires; keep access tokens short, as the refresh section shows.

Protecting API routes with a Guard

The usual shape: /login checks the user (left out here) and answers with a token from Issue, which adds exp, iat and the guard's algorithm. Every protected handler starts with a Require... call and returns at once when it is false. RequireScope reads the space separated scope claim, so the same token opens /orders but gets a 403 at /admin. The last request uses a token signed with the right secret but without exp; because the guard sets require_exp, it is refused.

jwt-guard.salam
import encoding.json
import jwt
import net.http
import net.router

mut guard := jwt.NewGuard("k8R2pX7wQ4mZ9vL1cT6yB3nH5sD0fG2a")

func login(ctx: i64):
    mut c := jwt.NewClaims()
    c.sub = http.Form(ctx, "user")
    jwt.SetStr(c, "scope", "orders:read")
    try:
        token := jwt.Issue(guard, c, 900)
        http.Json(ctx, "{\"token\":\"" + token + "\"}")
    catch e:
        http.SetStatus(ctx, 500)
        http.Text(ctx, e.message)
    end
end

func orders(ctx: i64):
    mut t := jwt.Token {}
    if not jwt.RequireScope(ctx, guard, "orders:read", t): ret end
    http.Json(ctx, "{\"orders_for\":\"" + t.claims.sub + "\"}")
end

func admin(ctx: i64):
    mut t := jwt.Token {}
    if not jwt.RequireScope(ctx, guard, "admin", t): ret end
    http.Text(ctx, "welcome, admin")
end

func call(path: str, token: str):
    mut headers := http.NewHeaders()
    if token.Len() > 0: headers.Insert("Authorization", "Bearer " + token) end
    r := http.GetWith("http://127.0.0.1:18661" + path, headers)
    println path, http.Status(r), http.Body(r)
end

func main:
    guard.opts.require_exp = true
    mut r := router.NewRouter()
    router.Post(r, "/login", login)
    router.Get(r, "/orders", orders)
    router.Get(r, "/admin", admin)
    mut s := http.NewServer(18661)
    http.SetHost(s, "127.0.0.1")
    http.Use(s, r)
    if not http.RunBackground(s):
        println "port 18661 is busy"
        ret 1
    end
    answer := http.Post("http://127.0.0.1:18661/login", "user=sara")
    token := json.Get(http.Body(answer), "token")
    call("/orders", "")
    call("/orders", token)
    call("/admin", token)

    mut forever := jwt.NewClaims()
    forever.sub = "sara"
    jwt.SetStr(forever, "scope", "orders:read")
    try:
        call("/orders", jwt.SignHS256(forever, guard.secret))
    catch e:
        println "could not sign:", e.message
    end
    ret 0
end
Output/orders 401 {"error":"unauthorized","reason":"missing bearer token"} /orders 200 {"orders_for":"sara"} /admin 403 {"error":"forbidden","reason":"missing scope: admin"} /orders 401 {"error":"unauthorized","reason":"required claim missing"}

Require takes the token from the Authorization: Bearer header, or from the cookie named in guard.cookie when there is no header. A 401 also carries a WWW-Authenticate header, as the HTTP rules ask.

Why a token is rejected

Verify checks, in order, that the token has three parts, that its algorithm is the one you expect, that the signature matches, and then the times and the claims you asked for in Options. It is declared throws, as are Decode, the Sign and Issue functions, Check and B64UrlDecode: the first failure is thrown as an Error. Catch it with try: ... catch e:, or write try before the call in a function that is itself throws to pass it on. e.message is a short reason and e.code a stable name to branch on. The program below fixes now so that it prints the same lines every time; in a server leave now at 0 and the current clock is used.

jwt-errors.salam
import jwt
import str

func report(label: str, token: str, secret: str, o: jwt.Options):
    try:
        _ := jwt.Verify(token, secret, o)
        println label + ": ok"
    catch e:
        println label + ": " + e.message + " (" + e.code + ")"
    end
end

func main throws:
    secret := "a-long-random-secret-for-this-demo"
    mut c := jwt.NewClaims()
    c.sub = "7"
    c.iss = "auth.example.com"
    c.iat = 1790000000
    c.nbf = 1790000000
    c.exp = 1790000900
    token := try jwt.SignHS256(c, secret)

    mut o := jwt.DefaultOptions()
    o.issuer = "auth.example.com"
    o.now = 1790000300
    report("fresh token", token, secret, o)
    report("wrong secret", token, "guess", o)

    parts := str.Split(token, ".")
    forged := parts.Get(0) + "." + jwt.B64UrlEncode("{\"sub\":\"1\",\"iss\":\"auth.example.com\"}") + "." + parts.Get(2)
    report("edited payload", forged, secret, o)

    o.now = 1790001000
    report("100 s after exp", token, secret, o)
    o.leeway = 120
    report("same, 120 s leeway", token, secret, o)

    o.leeway = 0
    o.now = 1789999000
    report("before nbf", token, secret, o)

    o.now = 1790000300
    o.issuer = "evil.example.com"
    report("other issuer", token, secret, o)

    strong := try jwt.SignHS512(c, secret)
    mut only256 := jwt.OptionsFor(jwt.JWT_HS256)
    only256.now = 1790000300
    report("HS512 token, HS256 expected", strong, secret, only256)
end
Outputfresh token: ok wrong secret: signature does not match (jwt.bad_signature) edited payload: signature does not match (jwt.bad_signature) 100 s after exp: token expired (jwt.expired) same, 120 s leeway: ok before nbf: token not yet valid (jwt.not_yet_valid) other issuer: issuer mismatch (jwt.bad_claim) HS512 token, HS256 expected: algorithm mismatch (jwt.alg_mismatch)

Three things to notice. Changing even one claim breaks the signature, so a client cannot raise its own rights. leeway forgives a small clock difference between the machine that signed and the one that checks; a minute or two is usual. And a token signed with HS512 is refused when the options say HS256: the algorithm comes from your options, never from the token, which is how this package avoids the classic alg attacks.

Every code the package throws:

e.codee.kindWhen
jwt.malformedSyntaxNot three parts separated by dots, or the header or the body part is empty.
jwt.bad_base64SyntaxA part is not url safe base64; e.path is header or payload and e.offset points into the token.
jwt.bad_jsonSyntaxThe header has no single alg, or a registered claim appears twice; e.path names it.
jwt.bad_algUnsupportedAn algorithm other than HS256, HS384 or HS512, none included.
jwt.bad_typUnsupportedThe typ header is not JWT or ...+jwt.
jwt.critUnsupportedThe header has a crit list, which this package does not understand.
jwt.empty_secretInvalidArgumentThe secret is empty, when signing or checking.
jwt.alg_mismatchPermissionDeniedThe token's algorithm is not the one in the options.
jwt.bad_signaturePermissionDeniedThe signature does not match.
jwt.expiredPermissionDeniedNow is at or past exp, after the leeway.
jwt.not_yet_validPermissionDeniedNow is before nbf.
jwt.issued_in_futurePermissionDeniedNow is before iat.
jwt.bad_claimPermissionDeniedThe issuer, subject or audience is not the one asked for; e.path is iss, sub or aud.
jwt.missing_claimMissingKeyA claim the options require is absent; e.path names it.
jwt.missing_tokenNotFoundCheck found no token in the request.

e.message is the short English reason, such as token expired; Require and its siblings send it as the reason of their 401. With Check you choose the answer yourself, as the /check route of the Guard example does: jwt.missing_token gets MissingCredential and every other code Unauthorized.

Short access tokens and a refresh token

A token cannot be taken back once issued, so access tokens should live for minutes, not days. To spare the user a new login every fifteen minutes, issue a second, long lived refresh token at login and accept it at one route only, where it buys a new access token. Mark each token with what it is for, so that a refresh token is refused as an access token. IssuePair on a Guard issues both in one call; the program does it by hand to show the checks.

jwt-refresh.salam
import jwt

func issue(subject: str, use: str, iat: i64, ttl: i64, secret: str): str throws:
    mut c := jwt.NewClaims()
    c.sub = subject
    c.iat = iat
    c.exp = iat + ttl
    jwt.SetStr(c, "use", use)
    ret try jwt.SignHS256(c, secret)
end

func accept(token: str, want: str, now: i64, secret: str): bool:
    mut o := jwt.DefaultOptions()
    o.now = now
    o.require_exp = true
    mut t := jwt.Token {}
    try:
        t = jwt.Verify(token, secret, o)
    catch e:
        println "  rejected:", e.message
        ret false
    end
    if jwt.Str(t, "use") != want:
        println "  rejected: wanted", want, "but got", jwt.Str(t, "use")
        ret false
    end
    ret true
end

func main throws:
    secret := "server-side-secret-of-at-least-32-bytes"
    login := 1790000000 as i64
    access := try issue("42", "access", login, 900, secret)
    refresh := try issue("42", "refresh", login, 30 * 86400, secret)

    println "request after 5 minutes:", accept(access, "access", login + 300, secret)
    println "request after 20 minutes:", accept(access, "access", login + 1200, secret)
    println "refresh after 20 minutes:", accept(refresh, "refresh", login + 1200, secret)
    new_access := try issue("42", "access", login + 1200, 900, secret)
    println "request with the new token:", accept(new_access, "access", login + 1300, secret)
    println "refresh token used as access:", accept(refresh, "access", login + 1300, secret)
end
Outputrequest after 5 minutes: true rejected: token expired request after 20 minutes: false refresh after 20 minutes: true request with the new token: true rejected: wanted access but got refresh refresh token used as access: false

Keep the refresh token in an HttpOnly cookie (SetSessionCookie) rather than in JavaScript, and store its jti on the server if you need to revoke it before it expires.

Rotating the secret

Sooner or later the secret has to change. If you switch at once, every user is logged out. Instead, give each secret a key id and put it in the token header with SignWithKid. To check a token, read its header with Decode, which does not verify anything, pick the secret for that kid, and only then call Verify. Sign new tokens with the new key and keep the old one until the last token signed with it has expired.

jwt-key-rotation.salam
import jwt

func secret_for(kid: str): str:
    keys := HashMap {} as HashMap<str, str>
    keys.Put("2026-09", "old-secret-kept-for-one-more-week")
    keys.Put("2026-10", "current-secret-used-for-new-tokens")
    if keys.Has(kid):
        ret keys.Get(kid)
    end
    ret ""
end

func check(token: str) throws:
    header := try jwt.Decode(token)
    secret := secret_for(header.kid)
    if secret.Len() == 0:
        println "kid", header.kid, "rejected: unknown key"
        ret
    end
    mut o := jwt.DefaultOptions()
    o.now = 1790000100
    t := try jwt.Verify(token, secret, o)
    println "kid", header.kid, "valid:", t.valid, "user:", t.claims.sub
end

func main throws:
    mut c := jwt.NewClaims()
    c.sub = "user-17"
    c.iat = 1790000000
    c.exp = 1790003600
    old := try jwt.SignWithKid(c, jwt.JWT_HS256, "2026-09", "old-secret-kept-for-one-more-week")
    fresh := try jwt.SignWithKid(c, jwt.JWT_HS256, "2026-10", "current-secret-used-for-new-tokens")
    stray := try jwt.SignWithKid(c, jwt.JWT_HS256, "2025-01", "a-secret-nobody-has-anymore")
    try check(old)
    try check(fresh)
    try check(stray)
end
Outputkid 2026-09 valid: true user: user-17 kid 2026-10 valid: true user: user-17 kid 2025-01 rejected: unknown key

Never trust anything else from Decode: the claims it returns are unverified, and only the key id is safe to use, because it only chooses which secret the real check runs with.

Which function for which job

JobUse
Protect HTTP routesNewGuard, then Require, RequireScope, RequireClaim or RequireSubject in each handler
Log a user inIssue or IssueFor, and SetSessionCookie for browsers
Access and refresh tokens togetherIssuePair
Sign a token outside HTTPNewClaims, SetStr and friends, then SignHS256
Check a token and read its claimsVerify, then Str, Int, Bool, HasScope
Only a yes or no answerIsValid
Read the key id before checkingDecode

Types

Token

struct Token
A decoded token.
NameTypeDescription
algstr = ""The signing algorithm, such as HS256.
typstr = ""The type, usually JWT.
kidstr = ""The key id, when the header carries one.
claimsClaimsThe standard claims.
header_jsonstr = ""The JSON text of the header.
payload_jsonstr = ""The JSON text of the body.
signing_inputstr = ""The part that was signed: the header and the body with a dot between them.
signaturestr = ""The signature as url safe base64.
validbool = falseThe signature and the times were checked and were right.
jwt-Sign.salam
import jwt

func reason(token: str, secret: str, o: jwt.Options): str:
    try:
        _ := jwt.Verify(token, secret, o)
        ret "ok"
    catch e:
        ret e.code + " " + e.message
    end
end

func main throws:
    mut c := jwt.NewClaims()
    c.iss = "salamlang.ir"
    c.sub = "42"
    c.aud = "api"
    c.iat = 1700000000
    c.exp = 1700003600
    jwt.SetStr(c, "name", "Maryam")
    jwt.SetInt(c, "level", 3)
    jwt.SetBool(c, "admin", false)
    jwt.SetRaw(c, "scope", `"read write"`)
    jwt.SetRaw(c, "roles", `["editor","viewer"]`)
    println jwt.ClaimsJSON(c)

    token := try jwt.SignHS256(c, "a-long-random-secret")
    println token.Len() > 0
    println token

    mut o := jwt.DefaultOptions()
    o.now = 1700001000
    o.issuer = "salamlang.ir"
    o.audience = "api"
    t := try jwt.Verify(token, "a-long-random-secret", o)
    println t.valid, t.alg, t.typ, t.claims.sub
    println jwt.Str(t, "name"), jwt.Int(t, "level"), jwt.Bool(t, "admin"), jwt.Has(t, "email")
    println jwt.Raw(t, "level"), jwt.HasScope(t, "write"), jwt.HasAudience(t, "api"), jwt.ListHas(t, "roles", "editor")

    println reason(token, "another-secret", o)
    o.now = 1800000000
    println reason(token, "a-long-random-secret", o)
    o.now = 1700001000
    o.issuer = "example.com"
    println jwt.IsValid(token, "a-long-random-secret", o)
    try:
        _ := jwt.Decode("abc")
    catch e:
        println e.code, e.is(ErrorKind.Syntax)
    end
end
Output{"iss":"salamlang.ir","sub":"42","aud":"api","exp":1700003600,"iat":1700000000,"name":"Maryam","level":3,"admin":false,"scope":"read write","roles":["editor","viewer"]} true eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzYWxhbWxhbmcuaXIiLCJzdWIiOiI0MiIsImF1ZCI6ImFwaSIsImV4cCI6MTcwMDAwMzYwMCwiaWF0IjoxNzAwMDAwMDAwLCJuYW1lIjoiTWFyeWFtIiwibGV2ZWwiOjMsImFkbWluIjpmYWxzZSwic2NvcGUiOiJyZWFkIHdyaXRlIiwicm9sZXMiOlsiZWRpdG9yIiwidmlld2VyIl19.MgapxUXhbCZqxlt0iTIEVfKD8kle6km_G6k_qIc_NoU true HS256 JWT 42 Maryam 3 false false 3 true true true jwt.bad_signature signature does not match jwt.expired token expired false jwt.malformed true

Guard

struct Guard
An HTTP route guard: the secret, the check options and the cookie name.
NameTypeDescription
secretstr = ""The signing secret.
optsOptionsThe check options.
cookiestr = ""The name of a cookie the token is also read from; empty means the Authorization header only.
realmstr = "api"The name that goes in the WWW-Authenticate header.
jwt-Guard.salam
import jwt
import net.http
import net.router

mut guard := jwt.NewGuard("a-server-secret-only-the-server-knows")

func login(ctx: i64):
    mut c := jwt.NewClaims()
    c.sub = "42"
    jwt.SetStr(c, "scope", "read")
    jwt.SetRaw(c, "roles", `["editor"]`)
    try:
        token := jwt.Issue(guard, c, 3600)
        jwt.SetSessionCookieInsecure(ctx, guard, token, 3600)
        http.Text(ctx, token)
    catch e:
        http.SetStatus(ctx, 500)
        http.Text(ctx, e.message)
    end
end

func me(ctx: i64):
    mut t := jwt.Token {}
    if jwt.Require(ctx, guard, t):
        http.Text(ctx, "hello user " + t.claims.sub)
    end
end

func admin(ctx: i64):
    mut t := jwt.Token {}
    if jwt.RequireScope(ctx, guard, "admin", t):
        http.Text(ctx, "admin panel")
    end
end

func edit(ctx: i64):
    mut t := jwt.Token {}
    if jwt.RequireClaim(ctx, guard, "roles", "editor", t):
        http.Text(ctx, "editor")
    end
end

func profile(ctx: i64):
    mut t := jwt.Token {}
    if jwt.RequireSubject(ctx, guard, http.Param(ctx, "id"), t):
        http.Text(ctx, "your own profile")
    end
end

func manual(ctx: i64):
    try:
        t := jwt.Check(ctx, guard)
        if t.claims.sub == "0":
            jwt.Forbidden(ctx, "the user is blocked")
        else:
            http.Text(ctx, "valid")
        end
    catch e:
        if e.code == "jwt.missing_token":
            jwt.MissingCredential(ctx, guard)
        else:
            jwt.Unauthorized(ctx, guard, e.message)
        end
    end
end

func login_secure(ctx: i64):
    try:
        token := jwt.IssueFor(guard, "42", 3600)
        jwt.SetSessionCookie(ctx, guard, token, 3600)
        http.Text(ctx, "signed in")
    catch e:
        http.SetStatus(ctx, 500)
        http.Text(ctx, e.message)
    end
end

func logout(ctx: i64):
    jwt.ClearSessionCookie(ctx, guard)
    http.Text(ctx, "you are logged out")
end

func main throws:
    guard.cookie = "session"
    mut r := router.NewRouter()
    router.Post(r, "/login", login)
    router.Get(r, "/me", me)
    router.Get(r, "/admin", admin)
    router.Get(r, "/edit", edit)
    router.Get(r, "/users/:id", profile)
    router.Get(r, "/check", manual)
    router.Post(r, "/login/secure", login_secure)
    router.Post(r, "/logout", logout)
    mut s := http.NewServer(19630)
    http.Use(s, r)
    _ := http.RunBackground(s)
    base := "http://127.0.0.1:19630"

    login_response := http.Post(base + "/login", "")
    token := http.Body(login_response)
    println http.CookieMap(login_response).Get("session") == token
    secure_response := http.Post(base + "/login/secure", "")
    println http.Body(secure_response), http.CookieMap(secure_response).Get("session").Len() > 0
    mut headers := http.NewHeaders()
    headers.Insert("Authorization", "Bearer " + token)
    println jwt.ParseBearer("Bearer " + token) == token
    ask(base, "/me", headers)
    ask(base, "/admin", headers)
    ask(base, "/edit", headers)
    ask(base, "/users/42", headers)
    ask(base, "/users/7", headers)
    ask(base, "/check", headers)
    ask(base, "/me", http.NewHeaders())
    mut bad := http.NewHeaders()
    bad.Insert("Authorization", "Bearer x.y.z")
    ask(base, "/check", bad)
    mut cookie := http.NewHeaders()
    cookie.Insert("Cookie", "session=" + token)
    ask(base, "/me", cookie)

    mut access := ""
    mut refresh := ""
    try jwt.IssuePair(guard, "42", 900, 86400, access, refresh)
    println access.Len() > 0, access != refresh
    one := try jwt.IssueFor(guard, "42", 60)
    checked := try jwt.Verify(one, guard.secret, guard.opts)
    println checked.claims.sub, guard.realm
end

func ask(base: str, path: str, headers: HashMap<str, str>):
    response := http.GetWith(base + path, headers)
    println path, http.Status(response), http.Body(response)
end
Outputtrue signed in true true /me 200 hello user 42 /admin 403 {"error":"forbidden","reason":"missing scope: admin"} /edit 200 editor /users/42 200 your own profile /users/7 403 {"error":"forbidden","reason":"not your resource"} /check 200 valid /me 401 {"error":"unauthorized","reason":"missing bearer token"} /check 401 {"error":"unauthorized","reason":"invalid base64url segment"} /me 200 hello user 42 true true 42 api

Claims

struct Claims
The claims of a token.
NameTypeDescription
issstr = ""The issuer.
substr = ""The subject, usually the user id.
audstr = ""The audience.
aud_rawstr = ""The audience as JSON, when it is an array.
expi64 = 0The expiry time in Unix seconds.
nbfi64 = 0The time before which it is not valid.
iati64 = 0The issue time.
jtistr = ""The unique id of the token.
extrastr = ""The other claims, as JSON.

The example for this item is shown with the ones above: jwt-Sign.salam

Options

struct Options
The check options.
NameTypeDescription
algstr = "HS256"The algorithm expected; a token with another one is rejected.
issuerstr = ""The required issuer; empty means do not check it.
audiencestr = ""The required audience.
subjectstr = ""The required subject.
leewayi64 = 0How many seconds of clock difference to accept.
nowi64 = 0The time to check against; zero means now. For testing.
require_expbool = falseReject a token with no exp. Off by default, so without it a token with no expiry is valid forever.
require_nbfbool = falseReject one with no nbf.
require_iatbool = falseReject one with no iat.
require_subbool = falseReject one with no sub.
require_jtibool = falseReject one with no jti.
check_typbool = trueCheck that the type is JWT.
jwt-Algorithms.salam
import jwt

func code_of(token: str, o: jwt.Options): str:
    try:
        _ := jwt.Verify(token, "k", o)
        ret "ok"
    catch e:
        ret e.code
    end
end

func main throws:
    println jwt.JWT_HS256, jwt.JWT_HS384, jwt.JWT_HS512
    println jwt.IsSupportedAlg("HS512"), jwt.IsSupportedAlg("none"), jwt.DigestSize("HS384")

    mut c := jwt.NewClaims()
    c.sub = "7"
    c.jti = "t-1"
    jwt.ExpiresIn(c, 3600)
    jwt.NotBeforeIn(c, 0)
    one := try jwt.SignHS384(c, "k")
    two := try jwt.SignHS512(c, "k")
    three := try jwt.Sign(c, jwt.JWT_HS256, "k")
    four := try jwt.SignWithKid(c, "HS256", "key-2026", "k")
    d1 := try jwt.Decode(one)
    d2 := try jwt.Decode(two)
    d4 := try jwt.Decode(four)
    println d1.alg, d2.alg, d4.kid

    t := try jwt.VerifyHS256(three, "k")
    println t.valid, jwt.SecondsRemaining(t) > 3500
    b := try jwt.Verify(one, "k", jwt.OptionsFor("HS384"))
    println b.valid
    println code_of(one, jwt.DefaultOptions())

    raw := try jwt.SignJSON(`{"sub":"1"}`, "HS256", "", "k")
    println raw
    d := try jwt.Decode(raw)
    println d.header_json, d.payload_json
    println jwt.SignatureOf(d.signing_input, "HS256", "k") == d.signature

    encoded := jwt.B64UrlEncode("hello?")
    println encoded.Len()
    println try jwt.B64UrlDecode(encoded)
    println jwt.B64UrlEncodeBytes("hi?" as void*, 3)
    try:
        _ := jwt.B64UrlDecode("aGk/")
    catch e:
        println e.code, e.offset, e.message
    end
    try:
        _ := jwt.SignHS256(c, "")
    catch e:
        println e.code, e.is(ErrorKind.InvalidArgument), e.message
    end
    mut strict := jwt.OptionsFor("HS384")
    strict.issuer = "salamlang.ir"
    println code_of(one, strict), code_of("a.b", strict), code_of("e30.e30.x", strict)
end
OutputHS256 HS384 HS512 true false 48 HS384 HS512 key-2026 true true true jwt.alg_mismatch eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.q9rSPf4ratZ1Xkhd3M-FudlLIKYdlSzrHeXV7AICSuw {"alg":"HS256","typ":"JWT"} {"sub":"1"} true 8 hello? aGk_ jwt.bad_base64 3 invalid character '/' jwt.empty_secret true empty secret jwt.bad_claim jwt.malformed jwt.bad_json

Constants and variables

JWT_HS256

const JWT_HS256: str = "HS256"
The HS256 algorithm.

The example for this item is shown with the ones above: jwt-Algorithms.salam

JWT_HS384

const JWT_HS384: str = "HS384"
The HS384 algorithm.

The example for this item is shown with the ones above: jwt-Algorithms.salam

JWT_HS512

const JWT_HS512: str = "HS512"
The HS512 algorithm.

The example for this item is shown with the ones above: jwt-Algorithms.salam

Functions

Has

func Has(t: Token, key: str): bool
The token has this claim.

The example for this item is shown with the ones above: jwt-Sign.salam

Raw

func Raw(t: Token, key: str): str
The JSON text of one claim.

The example for this item is shown with the ones above: jwt-Sign.salam

Str

func Str(t: Token, key: str): str
A string claim.

The example for this item is shown with the ones above: jwt-Sign.salam

Int

func Int(t: Token, key: str): i64
A numeric claim.

The example for this item is shown with the ones above: jwt-Sign.salam

Bool

func Bool(t: Token, key: str): bool
A boolean claim.

The example for this item is shown with the ones above: jwt-Sign.salam

HasAudience

func HasAudience(t: Token, want: str): bool
The audience of the token, whether a string or an array, has this value.

The example for this item is shown with the ones above: jwt-Sign.salam

ListHas

func ListHas(t: Token, key: str, want: str): bool
An array claim has this value; roles, for instance.

The example for this item is shown with the ones above: jwt-Sign.salam

HasScope

func HasScope(t: Token, want: str): bool
The scope claim, which separates scopes with spaces, has this scope.

The example for this item is shown with the ones above: jwt-Sign.salam

SecondsRemaining

func SecondsRemaining(t: Token): i64
How many seconds are left until the expiry; zero when it has expired.

The example for this item is shown with the ones above: jwt-Algorithms.salam

IsSupportedAlg

func IsSupportedAlg(alg: str): bool
This algorithm is supported.

The example for this item is shown with the ones above: jwt-Algorithms.salam

DigestSize

func DigestSize(alg: str): int
The signature length of the algorithm in bytes.

The example for this item is shown with the ones above: jwt-Algorithms.salam

Issue

func Issue(g: Guard, c: Claims, ttl: i64): Throws<str>
Throws like Sign. Sets exp to now plus ttl seconds and iat to now, fills in the guard's issuer and audience when the claims have none, and signs with the guard's algorithm.

The example for this item is shown with the ones above: jwt-Algorithms.salam

IssueFor

func IssueFor(g: Guard, subject: str, ttl: i64): Throws<str>
A token with nothing but a subject and an expiry.

The example for this item is shown with the ones above: jwt-Guard.salam

IssuePair

func IssuePair(g: Guard, subject: str, access_ttl: i64, refresh_ttl: i64, access &: str, refresh &: str): Throws<bool>
Makes a short lived access token and a long lived refresh token and puts them in access and refresh; the kind claim tells them apart. Throws like Issue, and then leaves both untouched.

The example for this item is shown with the ones above: jwt-Guard.salam

SetSessionCookie

func SetSessionCookie(ctx: i64, g: Guard, token: str, max_age: int)
Puts the token in the secure, HttpOnly cookie of the guard.

The example for this item is shown with the ones above: jwt-Guard.salam

SetSessionCookieInsecure

func SetSessionCookieInsecure(ctx: i64, g: Guard, token: str, max_age: int)
The same, without the Secure flag; for testing over HTTP only.

The example for this item is shown with the ones above: jwt-Guard.salam

ClearSessionCookie

func ClearSessionCookie(ctx: i64, g: Guard)
Clears the session cookie.

The example for this item is shown with the ones above: jwt-Guard.salam

NewGuard

func NewGuard(secret: str): Guard
A new guard with a secret and the default options; set opts.require_exp on it for APIs.

The example for this item is shown with the ones above: jwt-Guard.salam

ParseBearer

func ParseBearer(header_value: str): str
Pulls the token out of a Bearer ... header value.

The example for this item is shown with the ones above: jwt-Guard.salam

BearerToken

func BearerToken(ctx: i64): str
The token in the Authorization header of the request.

The example for this item is shown with the ones above: jwt-Guard.salam

TokenFrom

func TokenFrom(ctx: i64, g: Guard): str
The token of the request, from the header or the cookie of the guard.

The example for this item is shown with the ones above: jwt-Guard.salam

Check

func Check(ctx: i64, g: Guard): Throws<Token>
Checks the token of the request and sends no response itself. Throws jwt.missing_token when the request carries none, and otherwise whatever Verify throws.

The example for this item is shown with the ones above: jwt-Guard.salam

Unauthorized

func Unauthorized(ctx: i64, g: Guard, reason: str)
A 401 response with a reason.

The example for this item is shown with the ones above: jwt-Guard.salam

MissingCredential

func MissingCredential(ctx: i64, g: Guard)
A 401 response for a request that carries no token at all.

The example for this item is shown with the ones above: jwt-Guard.salam

Forbidden

func Forbidden(ctx: i64, reason: str)
A 403 response: the token is right but is not allowed.

The example for this item is shown with the ones above: jwt-Guard.salam

Require

func Require(ctx: i64, g: Guard, t &: Token): bool
Checks the token; when it is absent or wrong it sends the 401 response itself, with the error message as the reason, and returns false.

The example for this item is shown with the ones above: jwt-Guard.salam

RequireScope

func RequireScope(ctx: i64, g: Guard, scope: str, t &: Token): bool
The same, and the token has to carry this scope, otherwise 403.

The example for this item is shown with the ones above: jwt-Guard.salam

RequireClaim

func RequireClaim(ctx: i64, g: Guard, key: str, value: str, t &: Token): bool
The token has to carry this value in this array claim.

The example for this item is shown with the ones above: jwt-Guard.salam

RequireSubject

func RequireSubject(ctx: i64, g: Guard, subject: str, t &: Token): bool
The subject of the token has to be exactly this; so a user only reaches their own data.

The example for this item is shown with the ones above: jwt-Guard.salam

B64UrlEncodeBytes

func B64UrlEncodeBytes(p: void*, n: int): str
Turns bytes into url safe base64 without =.

The example for this item is shown with the ones above: jwt-Algorithms.salam

B64UrlEncode

func B64UrlEncode(s: str): str
Turns a string into url safe base64.

The example for this item is shown with the ones above: jwt-Algorithms.salam

B64UrlDecode

func B64UrlDecode(s: str): Throws<str>
Decodes url safe base64 without = padding. Throws Syntax at the offset of a character outside the url safe alphabet, and UnexpectedEnd when one character is left over; the code is jwt.bad_base64.

The example for this item is shown with the ones above: jwt-Algorithms.salam

SignJSON

func SignJSON(payload_json: str, alg: str, kid: str, secret: str): Throws<str>
Signs a JSON body you have already built. Throws jwt.bad_alg for an unsupported algorithm and jwt.empty_secret for an empty secret.

The example for this item is shown with the ones above: jwt-Algorithms.salam

SignatureOf

func SignatureOf(signing_input: str, alg: str, secret: str): str
Works out the signature of one input.

The example for this item is shown with the ones above: jwt-Algorithms.salam

SignWithKid

func SignWithKid(c: Claims, alg: str, kid: str, secret: str): Throws<str>
Like Sign, with a key id in the header; for rotating keys.

The example for this item is shown with the ones above: jwt-Algorithms.salam

Sign

func Sign(c: Claims, alg: str, secret: str): Throws<str>
Signs the claims with the given algorithm; throws like SignJSON.

The example for this item is shown with the ones above: jwt-Sign.salam

SignHS256

func SignHS256(c: Claims, secret: str): Throws<str>
Signs with HS256.

The example for this item is shown with the ones above: jwt-Sign.salam

SignHS384

func SignHS384(c: Claims, secret: str): Throws<str>
Signs with HS384.

The example for this item is shown with the ones above: jwt-Algorithms.salam

SignHS512

func SignHS512(c: Claims, secret: str): Throws<str>
Signs with HS512.

The example for this item is shown with the ones above: jwt-Algorithms.salam

NewClaims

func NewClaims(): Claims
Empty claims.

The example for this item is shown with the ones above: jwt-Sign.salam

SetStr

func SetStr(c &: Claims, key: str, value: str)
Adds a string claim.

The example for this item is shown with the ones above: jwt-Sign.salam

SetInt

func SetInt(c &: Claims, key: str, value: i64)
A numeric claim.

The example for this item is shown with the ones above: jwt-Sign.salam

SetBool

func SetBool(c &: Claims, key: str, value: bool)
A boolean claim.

The example for this item is shown with the ones above: jwt-Sign.salam

SetRaw

func SetRaw(c &: Claims, key: str, raw: str)
A claim with ready made JSON text, such as an array.

The example for this item is shown with the ones above: jwt-Sign.salam

ExpiresIn

func ExpiresIn(c &: Claims, seconds: i64)
Puts the expiry this many seconds from now.

The example for this item is shown with the ones above: jwt-Algorithms.salam

NotBeforeIn

func NotBeforeIn(c &: Claims, seconds: i64)
Puts the start of validity this many seconds from now.

The example for this item is shown with the ones above: jwt-Algorithms.salam

ClaimsJSON

func ClaimsJSON(c: Claims): str
The claims as JSON text.

The example for this item is shown with the ones above: jwt-Sign.salam

DefaultOptions

func DefaultOptions(): Options
The default options: HS256, no leeway, and no claim required, not even exp.

The example for this item is shown with the ones above: jwt-Sign.salam

OptionsFor

func OptionsFor(alg: str): Options
The default options with another algorithm.

The example for this item is shown with the ones above: jwt-Algorithms.salam

Decode

func Decode(token: str): Throws<Token>
Decodes a token without checking the signature; only to look at the contents, never to trust them. Throws jwt.malformed, jwt.bad_base64 or jwt.bad_json when it cannot be read.

The example for this item is shown with the ones above: jwt-Sign.salam

Verify

func Verify(token: str, secret: str, opts: Options): Throws<Token>
Checks the signature, the algorithm, the times and the claims the options ask for, and returns the token with valid set. Throws an Error with a jwt.* code at the first failure.

The example for this item is shown with the ones above: jwt-Sign.salam

VerifyHS256

func VerifyHS256(token: str, secret: str): Throws<Token>
Checks with HS256 and the default options; throws like Verify.

The example for this item is shown with the ones above: jwt-Algorithms.salam

IsValid

func IsValid(token: str, secret: str, opts: Options): bool
The token is valid; Verify without the error, for a plain yes or no.

The example for this item is shown with the ones above: jwt-Sign.salam