Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

jwt.core

import jwt

Everything here is re-exported by jwt, so import jwt is enough and the names are called as jwt.*. Importing jwt.core on its own works too and reaches the same definitions.

The core encode/decode/sign/verify functions the rest of the jwt module is built on. Verifier/Signer/Jwks are thin, stateful wrappers around verify()/sign() defined here.

Functions

encode()

jwt.encode(header, payload, secret, options) -> string

Encodes a header dictionary and payload dictionary into a signed JWT string.

This is the low-level encoding function. For most use cases, sign() is more convenient. Use encode() when you need full control over the header, such as when adding custom header parameters (kid, x5t, etc.).

The secret must be a string for HMAC algorithms, a PEM-encoded RSA private key for PS256/384/512, a PEM-encoded EC private key for ES256/384, or a PEM-encoded Ed25519 private key for EdDSA.

Parameters

  • header (dict) — must contain at minimum an ‘alg’ key
  • payload (dict)
  • secret (string)
  • options (?dict) — see sign() for supported option keys

Returns string

Raises AlgorithmError

Raises JwtError

decode()

jwt.decode(token) -> Token

Decodes a JWT string into a Token instance without performing signature verification or claim validation.

This function is useful for inspecting a token’s header or payload before deciding how to verify it (for example, to read the kid header parameter and look up the appropriate public key). It must not be used as the sole step when authenticating a request.

Parameters

  • token (string)

Returns Token

Raises MalformedTokenError

sign()

jwt.sign(payload, secret, options) -> string

Creates and signs a new JWT from the given payload.

The payload is merged with any registered claims derived from options before signing. Caller-supplied claims in payload always take precedence over option-derived claims.

Options

KeyTypeDefaultDescription
algorithmstringHS256Signing algorithm
expires_innumber:Token lifetime in seconds
not_beforenumber:Seconds until token becomes valid
issuerstring:Value for the iss claim
subjectstring:Value for the sub claim
audiencestring|list:Value for the aud claim
jwt_idstringautoValue for the jti claim
no_timestampboolfalseOmit the iat claim when true
headerdict:Extra header parameters
allow_noneboolfalsePermit the none algorithm

Example

import jwt

var token = jwt.sign(
  { user_id: 99, role: 'editor' },
  'my-secret-key',
  {
    algorithm: jwt.HS256,
    expires_in: 3600,
    issuer: 'api.example.com',
    subject: '99',
  }
)

Parameters

  • payload (dict)
  • secret (string)
  • options (?dict)

Returns string

Raises AlgorithmError

Raises JwtError

verify()

jwt.verify(token, secret, options) -> dict|Token

Verifies a JWT string and returns its payload (or the full Token when options.complete is true).

Verification performs the following steps in order:

  1. Structural decode: ensures the token is well-formed. 2. Algorithm check: rejects algorithms not in the options.algorithms list. 3. Signature verification: recomputes and compares the signature using a constant-time comparison for HMAC algorithms, or the underlying public-key verification for PS/ES/EdDSA algorithms. 4. Temporal claim validation: checks exp, nbf, and iat against the current clock, applying clock_tolerance leeway where configured. 5. Registered claim validation: checks iss, aud, and sub when the corresponding options are set.

An error is raised at the first failure; verification does not accumulate errors.

Options

KeyTypeDefaultDescription
algorithmslist[HS256,HS384,HS512]Accepted algorithm whitelist
issuerstring:Required iss claim value
subjectstring:Required sub claim value
audiencestring|list:Required aud claim value
clock_tolerancenumber0Leeway in seconds for exp, nbf, and iat
ignore_expirationboolfalseSkip exp validation
ignore_not_beforeboolfalseSkip nbf validation
completeboolfalseReturn full Token instead of payload dict
allow_noneboolfalsePermit the none algorithm

Example

import jwt

catch {
  var payload = jwt.verify(token, 'my-secret-key', {
    algorithms: [jwt.HS256],
    issuer: 'api.example.com',
    clock_tolerance: 5,
  })
  echo payload['user_id']
} as e

if e {
  # e is a JwtError
  echo 'token rejected: ' + e.message
}

Parameters

  • token (string)
  • secret (string)
  • options (dict)

Returns dict|Token

Raises MalformedTokenError

Raises AlgorithmError

Raises SignatureError

Raises TokenExpiredError

Raises ClaimError

jwt.header(token) -> dict

Returns the decoded header dictionary of a token without verifying its signature.

This is useful for reading the kid or alg header parameters before selecting the appropriate key or algorithm for full verification.

Parameters

  • token (string)

Returns dict

Raises MalformedTokenError

payload()

jwt.payload(token) -> dict

Returns the decoded payload dictionary of a token without verifying its signature.

Do not use this to make authorization decisions. Use verify() instead.

Parameters

  • token (string)

Returns dict

Raises MalformedTokenError

is_expired()

jwt.is_expired(token, leeway) -> bool

Returns true when the token’s exp claim is in the past, without verifying the signature.

A token without an exp claim is never considered expired by this function.

Parameters

  • token (string)
  • leeway (number) — Optional seconds of tolerance. Default: 0.

Returns bool

Raises MalformedTokenError

expires_in()

jwt.expires_in(token) -> number|nil

Returns the number of seconds until the token expires, based on its exp claim and the current clock. Returns nil when the token has no exp claim. Returns a negative number when the token has already expired.

Parameters

  • token (string)

Returns number|nil

Raises MalformedTokenError