LibJWT 3.5.0
The C JSON Web Token Library +JWK +JWKS

Create and sign JWT tokens. More...

Collaboration diagram for Builder:

Macros

#define jwt_builder_auto_t
 A jwt_builder_t pointer that is freed automatically at scope exit.

Typedefs

typedef struct jwt_builder jwt_builder_t
 Opaque Builder Object.
typedef struct jwt_signature jwt_signature_t
 An additional signer on a builder.

Enumerations

enum  jwt_serialization_t { JWT_FORMAT_COMPACT = 0 , JWT_FORMAT_JSON_FLAT , JWT_FORMAT_JSON_GENERAL }
 JWS serialization formats. More...

Functions

jwt_builder_tjwt_builder_new (void)
 Function to create a new builder instance.
void jwt_builder_free (jwt_builder_t *builder)
 Frees a previously created builder object.
int jwt_builder_error (const jwt_builder_t *builder)
 Checks error state of builder object.
const char * jwt_builder_error_msg (const jwt_builder_t *builder)
 Get the error message contained in a builder object.
void jwt_builder_error_clear (jwt_builder_t *builder)
 Clear error state in a builder object.
int jwt_builder_setkey (jwt_builder_t *builder, const jwt_alg_t alg, const jwk_item_t *key)
 Sets a key and algorithm for a builder.
int jwt_builder_set_format (jwt_builder_t *builder, jwt_serialization_t format)
 Select the serialization a builder emits.
jwt_signature_tjwt_builder_add_signature (jwt_builder_t *builder, jwt_alg_t alg, const jwk_item_t *key)
 Add an additional signer to a builder.
int jwt_signature_add_protected_json (jwt_signature_t *signature, const char *key, const char *value_json)
 Add a member to a signature's protected header.
int jwt_signature_add_header_json (jwt_signature_t *signature, const char *key, const char *value_json)
 Add a member to a signature's unprotected header.
int jwt_builder_setpayload (jwt_builder_t *builder, const unsigned char *data, size_t len)
 Sign an opaque (non-claims) payload.
int jwt_builder_setb64 (jwt_builder_t *builder, int b64)
 Select base64url or unencoded payload (RFC 7797).
int jwt_builder_set_detached (jwt_builder_t *builder, int detached)
 Detach the payload from the output.
int jwt_builder_settyp (jwt_builder_t *builder, const char *typ)
 Set the token media type ("typ" header).
int jwt_builder_enable_iat (jwt_builder_t *builder, int enable)
 Set IssuedAt usage on builder.
int jwt_builder_setcb (jwt_builder_t *builder, jwt_callback_t cb, void *ctx)
 Set a callback for generating tokens.
int jwt_builder_setjti (jwt_builder_t *builder, jwt_jti_gen_cb_t cb, void *ctx)
 Set a callback to generate the jti (JWT ID) claim (RFC-7519 Sec 4.1.7).
void * jwt_builder_getctx (jwt_builder_t *builder)
 Retrieve the callback context that was previously set.
int jwt_builder_setcrit (jwt_builder_t *builder, const char *header)
 Mark a header parameter as critical (RFC-7515 Sec 4.1.11).
char * jwt_builder_generate (jwt_builder_t *builder)
 Generate a token.

Detailed Description

Create and sign JWT tokens.

Creating a JWT token involves several steps. First is creating a jwt_builder_t object, which can be thought of as a JWT factory. Once configured, you can use it to create tokens with pre-defined claims.

Macro Definition Documentation

◆ jwt_builder_auto_t

#define jwt_builder_auto_t
Value:
jwt_builder_t \
__attribute__((cleanup(jwt_builder_freep)))

A jwt_builder_t pointer that is freed automatically at scope exit.

Declares a jwt_builder_t pointer carrying the GCC/Clang cleanup attribute so jwt_builder_free() is invoked on it automatically when the variable goes out of scope. Initialize it where you declare it.

Since
3.0.0

Typedef Documentation

◆ jwt_builder_t

typedef struct jwt_builder jwt_builder_t

Opaque Builder Object.

Since
3.0.0

◆ jwt_signature_t

typedef struct jwt_signature jwt_signature_t

An additional signer on a builder.

An opaque handle returned by jwt_builder_add_signature(), used to attach a per-signature protected or unprotected header. It is owned by the builder and is valid until jwt_builder_free(); the caller must not free it.

Since
3.6.0

Enumeration Type Documentation

◆ jwt_serialization_t

JWS serialization formats.

Selects what jwt_builder_generate() emits and is auto-detected by jwt_checker_verify() on input. The Compact Serialization (the default and historic behavior) is a single header.payload.signature string. The two JSON Serializations (RFC-7515 Sec 7.2) wrap one or more signatures in a JSON object and are the only forms that can carry multiple signatures or a per-signature unprotected header.

Since
3.6.0
Enumerator
JWT_FORMAT_COMPACT 

RFC-7515 Sec 7.1 Compact (default)

JWT_FORMAT_JSON_FLAT 

RFC-7515 Sec 7.2.2 Flattened (single sig)

JWT_FORMAT_JSON_GENERAL 

RFC-7515 Sec 7.2.1 General ("signatures":[])

Function Documentation

◆ jwt_builder_add_signature()

jwt_signature_t * jwt_builder_add_signature ( jwt_builder_t * builder,
jwt_alg_t alg,
const jwk_item_t * key )

Add an additional signer to a builder.

The first signer is set with jwt_builder_setkey(); this adds further ones for a multi-signature JWS JSON Serialization. The second signer automatically promotes the format to JWT_FORMAT_JSON_GENERAL. Each signature signs over its own protected header and the shared payload, so signers may use different algorithms (e.g. RS256 and ES256). alg must not be JWT_ALG_NONE.

Parameters
builderPointer to a builder object
algA valid jwt_alg_t type (not JWT_ALG_NONE)
keyA JWK private key matching alg
Returns
A borrowed jwt_signature_t handle (owned by the builder), or NULL on error with the error set in the builder
Since
3.6.0

◆ jwt_builder_enable_iat()

int jwt_builder_enable_iat ( jwt_builder_t * builder,
int enable )

Set IssuedAt usage on builder.

By default, the builder will set the iat claim to all tokens. You can enable or disable this using this function.

Parameters
builderPointer to a builder object
enable0 to disable, any other value to enable
Returns
Previous value (0 or 1), or -1 on error
Since
3.0.0

◆ jwt_builder_error()

int jwt_builder_error ( const jwt_builder_t * builder)

Checks error state of builder object.

Parameters
builderPointer to a builder object
Returns
0 if no errors exist, non-zero otherwise
Since
3.0.0

◆ jwt_builder_error_clear()

void jwt_builder_error_clear ( jwt_builder_t * builder)

Clear error state in a builder object.

Parameters
builderPointer to a builder object
Since
3.0.0

◆ jwt_builder_error_msg()

const char * jwt_builder_error_msg ( const jwt_builder_t * builder)

Get the error message contained in a builder object.

Parameters
builderPointer to a builder object
Returns
Pointer to a string with the error message. Can be an empty string if there is no error. Never returns NULL.
Since
3.0.0

◆ jwt_builder_free()

void jwt_builder_free ( jwt_builder_t * builder)

Frees a previously created builder object.

Parameters
builderPointer to a builder object
Since
3.0.0

◆ jwt_builder_generate()

char * jwt_builder_generate ( jwt_builder_t * builder)

Generate a token.

The result of this function is to generate a string containing a JWT. A token is represetned by 3 parts: header.payload.sig. Each part is Base64url Encoded. An example would be:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MzY0MzI0MzR9.iDn6N9JsAdUPF11ow0skIfc9eJc2wGRIq30RSRZ8_68

When decoded, the header and payload would look like this (excluding the signature block)::

{"alg":"HS256","typ":"JWT"}.{"iat":1736432434}

If pretty printed:

{
"alg": "HS256",
"typ": "JWT"
}
.
{
"iat": 1736432434
}

The signature block is a cryptographic hash. Its length and format is dependent on the algorithm being used.

A simple usage with no signature or payload would be:

jwt_builder_t *builder = NULL;
builder = jwt_builder_new();
if (builder) {
char *out = jwt_builder_generate(builder);
if (out) {
printf("%s\n", out);
free(out);
}
}
struct jwt_builder jwt_builder_t
Opaque Builder Object.
Definition jwt.h:424
jwt_builder_t * jwt_builder_new(void)
Function to create a new builder instance.
char * jwt_builder_generate(jwt_builder_t *builder)
Generate a token.
void jwt_builder_free(jwt_builder_t *builder)
Frees a previously created builder object.
Note
If you set a callback for this builder, this is when it will be called.
Parameters
builderPointer to a builder object
Returns
A string containing a JWT. Caller is respondible for freeing the memory for this string. On error, NULL is returned and error is set in the builder object.
Since
3.0.0

◆ jwt_builder_getctx()

void * jwt_builder_getctx ( jwt_builder_t * builder)

Retrieve the callback context that was previously set.

This is useful for accessing the context that was previously passed in the setcb function.

Parameters
builderPointer to a builder object
Returns
Pointer to the context or NULL
Since
3.0.0

◆ jwt_builder_new()

jwt_builder_t * jwt_builder_new ( void )

Function to create a new builder instance.

Returns
Pointer to a builder object on success, NULL on failure
Since
3.0.0

◆ jwt_builder_set_detached()

int jwt_builder_set_detached ( jwt_builder_t * builder,
int detached )

Detach the payload from the output.

With detached nonzero, the produced token omits the payload (an empty payload part in the Compact form, no "payload" member in the JSON forms). The verifier must supply the payload out-of-band with jwt_checker_verify_detached(). Orthogonal to jwt_builder_setb64().

Parameters
builderPointer to a builder object
detachedNonzero to omit the payload from the output
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.6.0

◆ jwt_builder_set_format()

int jwt_builder_set_format ( jwt_builder_t * builder,
jwt_serialization_t format )

Select the serialization a builder emits.

The default is JWT_FORMAT_COMPACT. Selecting a JSON form makes jwt_builder_generate() emit the JWS JSON Serialization. Adding a second signer with jwt_builder_add_signature() also forces JWT_FORMAT_JSON_GENERAL.

Parameters
builderPointer to a builder object
formatA jwt_serialization_t value
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.6.0

◆ jwt_builder_setb64()

int jwt_builder_setb64 ( jwt_builder_t * builder,
int b64 )

Select base64url or unencoded payload (RFC 7797).

With b64 nonzero (the default) the payload is base64url-encoded as usual. With b64 zero, 📄 RFC-7797 unencoded payloads are produced: "b64":false is emitted in the protected header, "b64" is added to "crit", and the signature is computed over the raw payload bytes. Requires a raw payload (jwt_builder_setpayload()), since RFC 7797 forbids the option for JWTs.

Parameters
builderPointer to a builder object
b64Nonzero for base64url (default), zero for an unencoded payload
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.6.0

◆ jwt_builder_setcb()

int jwt_builder_setcb ( jwt_builder_t * builder,
jwt_callback_t cb,
void * ctx )

Set a callback for generating tokens.

When generating a token, this callback will be run after jwt_t has been created, but before the token is encoded. During this, the callback can set, change, or remove claims and header attributes. It can also use the jwt_value_t structure to set a key and alg to use when signing the token.

The ctx value is also passed to the callback as part of the jwt_value_t struct.

Note
Calling this with a NULL cb param and a new ctx param after already setting the callback will allow updating the ctx passed to the callback. Calling with both values as NULL will disable the callback completely.
Parameters
builderPointer to a builder object
cbPointer to a callback function
ctxPointer to data to pass to the callback function
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.0.0

◆ jwt_builder_setcrit()

int jwt_builder_setcrit ( jwt_builder_t * builder,
const char * header )

Mark a header parameter as critical (RFC-7515 Sec 4.1.11).

Registers a header parameter name to be listed in the crit (Critical) header parameter of generated tokens. Use this when your application adds a custom (extension) header that a recipient MUST understand and process; per RFC 7515, a recipient that does not understand a listed parameter MUST reject the token.

Call this once for each name. The named header parameter must be present in the header when the token is generated (typically set in your callback), and it must not be a Header Parameter name defined by RFC 7515 or JWA (such as alg or typ); otherwise generation will fail. If no names are registered, no crit header is emitted.

Parameters
builderPointer to a builder object
headerName of the header parameter to mark as critical
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.4.0

◆ jwt_builder_setjti()

int jwt_builder_setjti ( jwt_builder_t * builder,
jwt_jti_gen_cb_t cb,
void * ctx )

Set a callback to generate the jti (JWT ID) claim (RFC-7519 Sec 4.1.7).

When set, the callback is run during generation to produce a unique jti for each token. The string it returns is set as the "jti" claim and then freed by LibJWT; returning NULL aborts generation. The application is responsible for guaranteeing uniqueness (the RFC requires a negligible collision probability, even across issuers).

The ctx is passed to the callback via the jwt_config_t structure.

Note
Calling this with a NULL cb and a new ctx updates the ctx. Calling with both NULL disables the callback.
Parameters
builderPointer to a builder object
cbPointer to a jti generation callback
ctxPointer to data to pass to the callback
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.4.0

◆ jwt_builder_setkey()

int jwt_builder_setkey ( jwt_builder_t * builder,
const jwt_alg_t alg,
const jwk_item_t * key )

Sets a key and algorithm for a builder.

The values here must make sense. This table shows what will or won't pass as far as algorithm matching between the alg param and the alg in jwk_item_t. Where alg-A means one specific algorithm (not none) and alg-B represents another (also not none). The none is used to represent no algorithm being set. NULL represents that jwk_item_t pointer is NULL.

alg jwt_item_t Result
alg-A alg-A
none alg-A
alg-A none
none NULL
alg-A alg-B
alg-A NULL
Warning
The warning represents an insecure token. Using insecure tokens is not very useful and strongly discouraged.
Parameters
builderPointer to a builder object
algA valid jwt_alg_t type
keyA JWK key object
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.0.0

◆ jwt_builder_setpayload()

int jwt_builder_setpayload ( jwt_builder_t * builder,
const unsigned char * data,
size_t len )

Sign an opaque (non-claims) payload.

Sets a raw payload to be signed verbatim instead of JSON claims, for a generic JWS (RFC 7515) — for example RFC 7797 unencoded payloads or a detached signature over an arbitrary document (JAdES). This is mutually exclusive with claims: when a raw payload is set it is used and any claims are ignored. Pass data as NULL (or len 0) to clear it and return to the claims model. The bytes are copied.

Parameters
builderPointer to a builder object
dataThe payload bytes (copied), or NULL to clear
lenThe payload length in bytes
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.6.0

◆ jwt_builder_settyp()

int jwt_builder_settyp ( jwt_builder_t * builder,
const char * typ )

Set the token media type ("typ" header).

A convenience setter for the "typ" header parameter, naming the token's media type — e.g. "at+jwt" (RFC 9068), "dpop+jwt", "secevent+jwt". Equivalent to setting the "typ" header directly. Pair it with jwt_checker_expect_typ() on the verifying side.

Parameters
builderPointer to a builder object
typThe media type string, or NULL to clear it
Returns
0 on success, non-zero otherwise with error set in the builder
Since
3.6.0

◆ jwt_signature_add_header_json()

int jwt_signature_add_header_json ( jwt_signature_t * signature,
const char * key,
const char * value_json )

Add a member to a signature's unprotected header.

The value is parsed as JSON. The member is NOT integrity-protected and is only emitted in the JSON serializations (RFC-7515 Sec 7.2.1). It must be disjoint from this signature's protected header.

Parameters
signatureA handle from jwt_builder_add_signature()
keyThe header parameter name
value_jsonThe value as a JSON string
Returns
0 on success, non-zero otherwise
Since
3.6.0

◆ jwt_signature_add_protected_json()

int jwt_signature_add_protected_json ( jwt_signature_t * signature,
const char * key,
const char * value_json )

Add a member to a signature's protected header.

The value is parsed as JSON. The member is integrity-protected (it is part of the bytes this signature signs over) and is the right place for a per-signer kid. Library-managed names (alg) and duplicates are rejected.

Parameters
signatureA handle from jwt_builder_add_signature()
keyThe header parameter name
value_jsonThe value as a JSON string
Returns
0 on success, non-zero otherwise
Since
3.6.0