|
LibJWT 3.8.0
The C JSON Web Token Library +JWK +JWKS
|
Create and sign JWT tokens. More...
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_t * | jwt_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_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. | |
| 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. | |
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.
| #define jwt_builder_auto_t |
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.
| typedef struct jwt_builder jwt_builder_t |
Opaque Builder Object.
| 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.
| enum 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.
| 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":[]) |
| 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.
This adds a signer of its own for a JWS JSON Serialization, beside the one jwt_builder_setkey() sets, whatever the order of the calls: the jwt_builder_setkey() signer's signature comes first, then these in the order they were added. jwt_builder_setkey() never changes or replaces a signer added here, so the returned handle keeps this key and its per-signature headers (jwt_signature_add_protected_json(), jwt_signature_add_header_json()) for every token, and a builder callback's key and algorithm (jwt_builder_setcb()) apply to the jwt_builder_setkey() signer only. The second signer, of either kind, automatically selects 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.
A Compact token carries only the jwt_builder_setkey() signer. If the only signer was added with this function, select JWT_FORMAT_JSON_FLAT or JWT_FORMAT_JSON_GENERAL: in JWT_FORMAT_COMPACT, jwt_builder_generate() fails rather than emit a token without it (also after jwt_builder_setkey(::JWT_ALG_NONE, NULL), which removes only the jwt_builder_setkey() signer).
A key that is in error (jwks_item_error()) is refused, and no signer is added. As with jwt_builder_setkey(), the builder then emits no unsigned token in its place.
| builder | Pointer to a builder object |
| alg | A valid jwt_alg_t type (not JWT_ALG_NONE) |
| key | A JWK private key matching alg (one in error is refused) |
| 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.
| builder | Pointer to a builder object |
| enable | 0 to disable, any other value to enable |
| int jwt_builder_error | ( | const jwt_builder_t * | builder | ) |
Checks error state of builder object.
| builder | Pointer to a builder object |
| void jwt_builder_error_clear | ( | jwt_builder_t * | builder | ) |
Clear error state in a builder object.
| builder | Pointer to a builder object |
| const char * jwt_builder_error_msg | ( | const jwt_builder_t * | builder | ) |
Get the error message contained in a builder object.
| builder | Pointer to a builder object |
| void jwt_builder_free | ( | jwt_builder_t * | builder | ) |
Frees a previously created builder object.
| builder | Pointer to a builder object |
| 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:
When decoded, the header and payload would look like this (excluding the signature block)::
If pretty printed:
The signature block is a cryptographic hash. Its length and format is dependent on the algorithm being used.
A signed token gets the "typ":"JWT" above only when its header has no typ: an application's own is kept, a JSON null one included (before 3.8.0, json-c replaced a null one).
A simple usage with no signature or payload would be:
| builder | Pointer to a builder object |
| 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.
| builder | Pointer to a builder object |
| jwt_builder_t * jwt_builder_new | ( | void | ) |
Function to create a new builder instance.
| 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().
| builder | Pointer to a builder object |
| detached | Nonzero to omit the payload from the output |
| 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() or with jwt_builder_setkey() beside one, also selects JWT_FORMAT_JSON_GENERAL. A format selected after that stands: jwt_builder_generate() then fails rather than drop a signer from a form that carries only one.
| builder | Pointer to a builder object |
| format | A jwt_serialization_t value |
| 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.
The result is not a JWT, even if its bytes spell a claim set: a checker evaluates it as an empty claim set, so claim pins, jwt_checker_require() or a jti callback reject it (see jwt_checker_verify()).
The setting applies to every signature of a JSON serialization alike, as RFC-7797 Sec 3 requires, and is the only way to set "b64": jwt_builder_header_set(), jwt_signature_add_protected_json() and jwt_signature_add_header_json() refuse it, and jwt_builder_generate() fails if a callback sets a "b64" header that does not match it.
| builder | Pointer to a builder object |
| b64 | Nonzero for base64url (default), zero for an unencoded payload |
| 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 config's key and alg start out as the jwt_builder_setkey() signer's (none, if it was not set), and whatever the callback leaves there makes that signer's signature, in every format: the Compact token's, and the first signature of a JSON one. When jwt_builder_setkey() was not called, a key the callback sets acts as that signer for this token (in a JSON form, one more signature, ahead of the jwt_builder_add_signature() ones). Given a key and JWT_ALG_NONE, it signs with the key's own "alg". The jwt_builder_add_signature() signers always keep their own key and algorithm. A JSON form cannot carry an unsigned signature, so jwt_builder_generate() fails if the callback takes the key away from a jwt_builder_setkey() signer.
The ctx value is also passed to the callback as part of the jwt_value_t struct.
| builder | Pointer to a builder object |
| cb | Pointer to a callback function |
| ctx | Pointer to data to pass to the callback function |
| 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. A parameter whose value is JSON null is present (before 3.8.0, json-c failed generation over it).
| builder | Pointer to a builder object |
| header | Name of the header parameter to mark as critical |
| 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.
| builder | Pointer to a builder object |
| cb | Pointer to a jti generation callback |
| ctx | Pointer to data to pass to the callback |
| 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 | ❌ |
A key that is in error (jwks_item_error()) is refused, whatever alg is, and the builder keeps the key it has. A builder that has none is not left to produce unsigned tokens for an application that ignores the failure: jwt_builder_generate() fails rather than emit one, until this function succeeds (with a key that works, or with JWT_ALG_NONE and a NULL key to ask for unsigned tokens) or a callback supplies the key.
The setkey() signer. This function owns one signer of its own, apart from the ones jwt_builder_add_signature() adds, whatever the order of the calls. The first call with a key makes it, the first signature of the token; later calls replace its key and algorithm; JWT_ALG_NONE with a NULL key removes it. It never changes or replaces a jwt_builder_add_signature() signer, which keeps its key and its per-signature headers. With such a signer present, adding this one makes two signers and selects JWT_FORMAT_JSON_GENERAL, as a second jwt_builder_add_signature() does (a later jwt_builder_set_format() still applies, and then jwt_builder_generate() fails for a form that cannot carry them all).
A Compact token (JWT_FORMAT_COMPACT) carries this signer only: if a jwt_builder_add_signature() signer is set, jwt_builder_generate() fails rather than emit a Compact token without it, so removing this signer never leaves an unsigned Compact token in place of one. A builder callback (jwt_builder_setcb()) that sets a key and algorithm signs this signer's signature with them, in every format.
| builder | Pointer to a builder object |
| alg | A valid jwt_alg_t type |
| key | A JWK key object |
| 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.
jwt_checker_verify() reads a base64url-encoded (the default) payload as a JWT claim set, so it must then be a JSON object; an unencoded one (jwt_builder_setb64()) is never claims (RFC-7797 Sec 7), so a checker that pins or requires claims rejects it.
| builder | Pointer to a builder object |
| data | The payload bytes (copied), or NULL to clear |
| len | The payload length in bytes |
| 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.
| builder | Pointer to a builder object |
| typ | The media type string, or NULL to clear it |
| 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, in which a parameter whose value is JSON null counts (with either JSON backend; before 3.8.0, json-c let such a name through to both headers). crit and b64 must be integrity protected (RFC-7515 Sec 4.1.11, RFC-7797 Sec 3) and are rejected here, as are alg and duplicates; jwt_checker_verify() rejects a token that carries either one unprotected.
| signature | A handle from jwt_builder_add_signature() |
| key | The header parameter name |
| value_json | The value as a JSON string |
| 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 and duplicates are rejected: the library sets alg from the signer, and b64 from jwt_builder_setb64() for every signature alike, since it describes the shared payload (RFC-7797 Sec 3).
A crit (RFC-7515 Sec 4.1.11) set here lists this signature's own critical parameters. Like the builder's crit, it must be a non-empty array of distinct names that RFC 7515 and JWA do not define, each present in this signature's protected header, which includes the builder's header (a member set with jwt_signature_add_header_json() does not count). jwt_builder_generate() lists the builder's critical names (its crit header, jwt_builder_setcrit(), and b64 for an unencoded payload) first and this signature's others after them, and fails rather than emit an invalid crit.
| signature | A handle from jwt_builder_add_signature() |
| key | The header parameter name |
| value_json | The value as a JSON string |