### Configure and install pkg-config file Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Configures libjwt.pc from libjwt.pc.in with @ONLY substitution and installs it to the pkgconfig directory. ```cmake configure_file(libjwt/libjwt.pc.in libjwt.pc @ONLY) install(FILES ${CMAKE_BINARY_DIR}/libjwt.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) ``` -------------------------------- ### Install headers and documentation Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Installs the public header jwt.h, the generated export header, and the LICENSE and README files to their respective destinations. ```cmake install(FILES include/jwt.h ${CMAKE_BINARY_DIR}/jwt_export.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(FILES LICENSE README.md DESTINATION ${CMAKE_INSTALL_DOCDIR}) ``` -------------------------------- ### Install shared and static libraries Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Installs the shared library jwt and the static library jwt_static, exporting them with separate export names. ```cmake install(TARGETS jwt EXPORT ${LIBJWT_PROJECT}Targets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) # Install Static library install(TARGETS jwt_static EXPORT ${LIBJWT_PROJECT}StaticTargets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) ``` -------------------------------- ### Build and install command-line tools Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Invokes jwt_add_tool for each tool (jwt-verify, jwt-generate, jwk2key, key2jwk, jwe-encrypt, jwe-decrypt) and installs man pages from the tools directory. ```cmake jwt_add_tool(NAME jwt-verify SRC tools/jwt-verify.c) jwt_add_tool(NAME jwt-generate SRC tools/jwt-generate.c) jwt_add_tool(NAME jwk2key SRC tools/jwk2key.c) jwt_add_tool(NAME key2jwk SRC tools/key2jwk.c) jwt_add_tool(NAME jwe-encrypt SRC tools/jwe-encrypt.c) jwt_add_tool(NAME jwe-decrypt SRC tools/jwe-decrypt.c) install(DIRECTORY ${CMAKE_SOURCE_DIR}/tools/ DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 FILES_MATCHING PATTERN "*.1") ``` -------------------------------- ### key2jwk example output for Ed25519 key Source: https://github.com/benmcollins/libjwt/blob/master/tools/key2jwk.1.md Example output from running key2jwk with the -q and -o - options on an Ed25519 private key file. The output is a JWK Set in JSON format, including a comment, date, hostname, and the key with key_ops, kty, crv, alg, x, d, and kid attributes. ```json $ key2jwk -q -o - eddsa_key_ed25519.pem { "libjwt.io:comment": "Generated by LibJWT 2.9.99", "libjwt.io:date": "Sun Jan 12 23:50:24 2025", "libjwt.io:hostname": "maClara.local", "keys": [ { "key_ops": [ "sign" ], "kty": "OKP", "crv": "Ed25519", "alg": "EdDSA", "x": "HUj-14kN6N4i5qNVkfEhwKiCf-tSrvRHstQdtV8a5QM", "d": "XY5oUZqGWVZhX7J09hG-rRnAKXiw1g_aBh-Bc52KZ_Y", "kid": "yP8YONwTmFovdfeOfp9y5u_lxzP7Y3JAmpUgeNnXFS8" } ] } ``` -------------------------------- ### Install CMake package config Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Installs the CMake package configuration file for the shared library targets, enabling find_package support. ```cmake install(EXPORT ${LIBJWT_PROJECT}Targets FILE ${LIBJWT_PROJECT}Config.cmake NAMESPACE ${LIBJWT_PROJECT}:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${LIBJWT_PROJECT} ) ``` -------------------------------- ### Find Doxygen and generate documentation Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Finds Doxygen 1.9.8 and, if found, sets the output directory, includes LibJWTDoxyfile, adds a doxygen target for include/jwt.h, and installs man pages and HTML documentation. ```cmake find_package(Doxygen 1.9.8) if (DOXYGEN_FOUND) set(DOXYGEN_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/doxygen-doc) include(LibJWTDoxyfile) doxygen_add_docs(doxygen-doc ALL include/jwt.h) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen-doc/man/man3/ DESTINATION ${CMAKE_INSTALL_MANDIR}/man3 FILES_MATCHING PATTERN "man3/JW*.3" PATTERN "man3/jw*.3") install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen-doc/html/ DESTINATION ${CMAKE_INSTALL_DOCDIR}/html/) endif() ``` -------------------------------- ### Define jwt_add_tool function Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Defines a CMake function that creates an executable from a source file, links it privately to jwt, sets the runtime output directory, and installs it. ```cmake set(TOOLS) function(jwt_add_tool) set(oneValueArgs NAME SRC DIR) cmake_parse_arguments(Tool "" "${oneValueArgs}" "" ${ARGN}) list(APPEND TOOLS ${Tool_NAME}) add_executable(${Tool_NAME} ${Tool_SRC}) # Tools use only the public libjwt API; they need no crypto backend link. target_link_libraries(${Tool_NAME} PRIVATE jwt) set_target_properties(${Tool_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tools") install(TARGETS ${Tool_NAME} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) endfunction() ``` -------------------------------- ### jwks_load_fromurl_cached Source: https://github.com/benmcollins/libjwt/blob/master/README.md Fetches a JWKS from a URL and caches the keyring. Subsequent calls serve cached keys while fresh, honoring Cache-Control max-age or a configurable TTL. Stale cache is refreshed with conditional GET. ```APIDOC ## jwks_load_fromurl_cached ### Description Fetches a JWKS from a URL and caches the keyring. Subsequent calls serve cached keys while fresh, honoring Cache-Control max-age or a configurable TTL. Stale cache is refreshed with conditional GET. ### Method C function ### Signature ```c jwk_set_t *jwks_load_fromurl_cached(const char *url, ...); ``` ### Parameters - **url** (const char*) - Required - The URL to fetch (http/https only). - Additional parameters may be required for cache configuration (not specified in source). ### Return Value - **jwk_set_t*** - The JWK set. ### Notes - Requires WITH_LIBCURL build. - Only http/https URLs accepted (SSRF guard). - Uses If-None-Match/ETag for conditional GET; 304 keeps keys. ``` -------------------------------- ### Encrypting to a recipient's public key with RSA-OAEP-256 Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Uses the recipient's public RSA JWK to encrypt a message with RSA-OAEP-256 key management. Only the algorithm changes from the symmetric example; the rest of the flow is identical. The recipient decrypts with their private key. ```c /* The sender needs only the recipient's public RSA JWK. */ keys = jwks_create_fromfile("rsa_key_2048_enc.json"); key = jwks_item_get(keys, 0); builder = jwe_builder_new(); jwe_builder_setkey(builder, JWE_ALG_RSA_OAEP_256, JWE_ENC_A256GCM, key); token = jwe_builder_generate(builder, (const unsigned char *)message, strlen(message)); ``` -------------------------------- ### Build with backend options Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md CMake configuration enabling GnuTLS, mbedTLS, libcurl, and json-c backends. Switching backends in an existing build resets unspecified flags; re-pass all flags and run make clean after switching. ```bash cmake -DWITH_GNUTLS=ON -DWITH_MBEDTLS=ON -DWITH_LIBCURL=ON -DWITH_JSON_C=ON .. ``` -------------------------------- ### Standard build commands Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md Commands to create a build directory, configure with CMake, and compile the project. ```bash mkdir build && cd build cmake .. make ``` -------------------------------- ### Run all tests Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md Runs the full test suite via make check. ```bash make check ``` -------------------------------- ### Include CPack configuration Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Sets the CPack properties file and includes CPack to enable packaging. ```cmake set(CPACK_PROPERTIES_FILE "${CMAKE_SOURCE_DIR}/cmake/CPackConfig.cmake") include(CPack) ``` -------------------------------- ### Dynamic token generation with a callback Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Shows how to set per-token claims and choose the signing key at generation time using a callback registered with jwt_builder_setcb. The callback receives a context pointer and returns non-zero to abort generation. ```c /* Set a per-token claim and choose the signing key at generation time. */ static int on_generate(jwt_t *jwt, jwt_config_t *config) { jwt_value_t jval; const char *user = config->ctx; /* the ctx we registered below */ jwt_set_SET_STR(&jval, "sub", user); jwt_claim_set(jwt, &jval); config->alg = JWT_ALG_HS256; config->key = my_lookup_key(user); /* application-provided */ return 0; /* non-zero aborts generation */ } /* Register it, passing a context pointer through to the callback. */ jwt_builder_setcb(builder, on_generate, "user@example.com"); token = jwt_builder_generate(builder); ``` -------------------------------- ### Verify DPoP proof with cnf.jkt binding (RFC 9449) Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/profiles.dox Shows the full DPoP verification flow: bind the access token to the client key via cnf.jkt, create a proof with the client key in the header and an 'ath' claim, then verify the proof at the resource server. In a callback, compare the proof's 'ath' to the token hash and check htm/htu. ```c /* The access token was bound to the client key: */ jwt_builder_setcnf_jkt(at_builder, client_key); /* -> cnf.jkt */ /* The proof carries the client key in its header and hashes the AT: */ char *ath = jwt_token_hash(access_token, JWK_THUMBPRINT_SHA256); /* ...set proof header "jwk", claims htm/htu/jti/ath, sign with client_key... */ /* Verify the proof at the resource server: */ char *jkt = jwt_get_cnf(verified_access_token, "jkt"); /* the binding */ jwt_checker_expect_typ(checker, "dpop+jwt"); jwt_checker_enable_embedded_jwk(checker, JWK_THUMBPRINT_SHA256, jkt); jwt_checker_verify(checker, proof); /* In a jwt_checker_setcb() callback, compare the proof's "ath" to * jwt_token_hash(access_token, JWK_THUMBPRINT_SHA256) and check htm/htu. */ free(ath); free(jkt); ``` -------------------------------- ### Configure and run code coverage Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md Commands to enable coverage and run the coverage check. Note that make check-code-coverage always exits non-zero due to a final genhtml failure; read per-line coverage from build/check-code-coverage.capture. ```bash cmake -DENABLE_COVERAGE=YES .. make check-code-coverage ``` -------------------------------- ### Add global compile definitions Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Adds _GNU_SOURCE and defines KEYDIR pointing to the tests/keys directory. ```cmake add_definitions(-D_GNU_SOURCE -DKEYDIR=\"${CMAKE_SOURCE_DIR}/tests/keys\") ``` -------------------------------- ### Check for crypto support and define library targets Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Fails the build if no crypto support is detected, then adds the source files to both shared and static library targets and sets public include directories. ```cmake if (NOT HAVE_CRYPTO) message(FATAL_ERROR "No crypto support detected") endif() target_sources(jwt PRIVATE ${JWT_SOURCES}) target_sources(jwt_static PRIVATE ${JWT_SOURCES}) target_include_directories(jwt PUBLIC $ $ ) ``` -------------------------------- ### Generate JWE with ECDH-ES and PartyInfo (apu/apv) Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Sets up a builder with an EC key and ECDH-ES algorithm, optionally binding PartyUInfo and PartyVInfo into the key derivation. These values are emitted as 'apu' and 'apv' headers in the token. ```c keys = jwks_create_fromfile("ec_key_prime256v1_enc.json"); key = jwks_item_get(keys, 0); builder = jwe_builder_new(); jwe_builder_setkey(builder, JWE_ALG_ECDH_ES, JWE_ENC_A256GCM, key); /* Optional context bound into the key derivation. */ jwe_builder_set_partyinfo(builder, (const unsigned char *)"Alice", 5, /* apu */ (const unsigned char *)"Bob", 3); /* apv */ token = jwe_builder_generate(builder, (const unsigned char *)message, strlen(message)); ``` -------------------------------- ### Experimental ML-DSA support detection (OpenSSL >= 3.5 or GnuTLS >= 3.8.10) Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Enables LIBJWT_HAVE_ML_DSA when a capable backend is found. Requires OpenSSL >= 3.5 or GnuTLS >= 3.8.10 (with a PQC provider). Emits a warning if requested but no backend supports it. Do not bump the version floors; these are additive checks. ```cmake # Experimental ML-DSA (FIPS 204 / RFC 9964) support. Implemented by OpenSSL # >= 3.5 and by GnuTLS >= 3.8.10 (the latter requires a GnuTLS built with a # PQC provider, e.g. --with-leancrypto); MbedTLS has no ML-DSA and cleanly # rejects AKP keys. This drives the public LIBJWT_HAVE_ML_DSA macro (emitted in # jwt_export.h) which gates the backend-independent ML-DSA code; each backend's # own code is additionally guarded by its own version check. Do NOT bump the # OpenSSL/GnuTLS floors above; these are additive capability checks. if (WITH_ML_DSA) set(_mldsa_via "") if (OPENSSL_FOUND AND OPENSSL_VERSION VERSION_GREATER_EQUAL 3.5) set(_mldsa_via "${_mldsa_via} OpenSSL ${OPENSSL_VERSION}") endif() if (GNUTLS_FOUND AND GNUTLS_VERSION VERSION_GREATER_EQUAL 3.8.10) set(_mldsa_via "${_mldsa_via} GnuTLS ${GNUTLS_VERSION}") endif() if (_mldsa_via) set(LIBJWT_HAVE_ML_DSA ON) message(STATUS "ML-DSA (experimental) enabled via:${_mldsa_via}") else() message(WARNING "WITH_ML_DSA was requested but no capable crypto backend " "was found (needs OpenSSL >= 3.5 or GnuTLS >= 3.8.10); " "ML-DSA stays disabled") endif() endif() ``` -------------------------------- ### Crypto backend detection (GnuTLS, mbedTLS, OpenSSL) Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Sets HAVE_CRYPTO and adds definitions and links for each detected crypto backend, appending backend-specific source files to JWT_SOURCES. ```cmake # Process the detected packages set(HAVE_CRYPTO FALSE) if (GNUTLS_FOUND) set(HAVE_CRYPTO TRUE) add_definitions(-DHAVE_GNUTLS) target_link_libraries(jwt PUBLIC PkgConfig::GNUTLS) target_link_libraries(jwt_static PUBLIC PkgConfig::GNUTLS) list(APPEND JWT_SOURCES libjwt/gnutls/jwk-parse.c libjwt/gnutls/jwk-export.c libjwt/gnutls/sign-verify.c libjwt/gnutls/jwe.c) endif() if (MBEDTLS_FOUND) set(HAVE_CRYPTO TRUE) add_definitions(-DHAVE_MBEDTLS) target_link_libraries(jwt PUBLIC PkgConfig::MBEDTLS) target_link_libraries(jwt_static PUBLIC PkgConfig::MBEDTLS) list(APPEND JWT_SOURCES libjwt/mbedtls/jwk-parse.c libjwt/mbedtls/jwk-export.c libjwt/mbedtls/sign-verify.c libjwt/mbedtls/jwe.c) endif() if (OPENSSL_FOUND) set(HAVE_CRYPTO TRUE) add_definitions(-DHAVE_OPENSSL) target_link_libraries(jwt PUBLIC PkgConfig::OPENSSL) target_link_libraries(jwt_static PUBLIC PkgConfig::OPENSSL) list(APPEND JWT_SOURCES libjwt/openssl/jwk-parse.c libjwt/openssl/jwk-export.c libjwt/openssl/sign-verify.c libjwt/openssl/jwe.c) endif() ``` -------------------------------- ### jwks_create_fromfile Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Loads a JWK set from a file. ```APIDOC ## jwks_create_fromfile ### Description Loads a JWK set from a file. ### Parameters - **file** (const char *) - Required - Path to the JWK set file. ### Returns - **jwk_set_t *** - The loaded JWK set. ``` -------------------------------- ### Create source tarball with git archive Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md Command to build the source tarball for a release, excluding .github/ and .gitignore, rooted under libjwt-X.Y.Z/, and compressed with xz. ```bash git archive --format=tar --prefix=libjwt-X.Y.Z/ vX.Y.Z \ -- . ':(exclude).github' ':(exclude).gitignore' | xz -9 -c > libjwt-X.Y.Z.tar.xz ``` -------------------------------- ### Signing your first token with HS256 Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Loads an octet key from a JWK file, creates a jwt_builder_t, sets the key with JWT_ALG_HS256, and generates a token. The caller owns the returned token string. By default, the builder adds an 'iat' claim; disable with jwt_builder_enable_iat. ```c #include #include #include int main(void) { jwt_builder_t *builder = NULL; jwk_set_t *keys = NULL; const jwk_item_t *key = NULL; char *token = NULL; /* Load the signing key (a JWK with "kty":"oct"). */ keys = jwks_create_fromfile("oct_key_256.json"); key = jwks_item_get(keys, 0); /* Create the builder and give it the key + algorithm. */ builder = jwt_builder_new(); jwt_builder_setkey(builder, JWT_ALG_HS256, key); /* Generate the token. The caller owns the returned string. */ token = jwt_builder_generate(builder); if (token == NULL) fprintf(stderr, "generate failed: %s\n", jwt_builder_error_msg(builder)); else printf("%s\n", token); free(token); jwt_builder_free(builder); jwks_free(keys); return 0; } ``` -------------------------------- ### Encrypting a message with jwe_builder_generate Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Shows how to generate a compact JWE token using a builder configured with a key. The token is printed or an error message is shown. The builder and key set are freed after use. ```c token = jwe_builder_generate(builder, (const unsigned char *)message, strlen(message)); if (token == NULL) fprintf(stderr, "encrypt failed: %s\n", jwe_builder_error_msg(builder)); else printf("%s\n", token); /* a five-part compact JWE */ free(token); jwe_builder_free(builder); jwks_free(keys); ``` -------------------------------- ### Verifying a token with HS256 Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Loads the same key, creates a jwt_checker_t, sets the key with JWT_ALG_HS256, and calls jwt_checker_verify. A return of 0 means the signature and any configured claim checks passed. Pinning the algorithm prevents algorithm-confusion attacks. ```c jwt_checker_t *checker = NULL; jwk_set_t *keys = NULL; const jwk_item_t *key = NULL; keys = jwks_create_fromfile("oct_key_256.json"); key = jwks_item_get(keys, 0); checker = jwt_checker_new(); jwt_checker_setkey(checker, JWT_ALG_HS256, key); if (jwt_checker_verify(checker, token) == 0) printf("token is valid\n"); else printf("rejected: %s\n", jwt_checker_error_msg(checker)); jwt_checker_free(checker); jwks_free(keys); ``` -------------------------------- ### Adding claims to a builder with jwt_value_t Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Shows how to set string and integer claims on a jwt_builder_t using jwt_value_t and the jwt_set_SET_* macros. Claims set on the builder are copied into every token it generates. ```c jwt_value_t jval; /* "sub": "user@example.com" */ jwt_set_SET_STR(&jval, "sub", "user@example.com"); jwt_builder_claim_set(builder, &jval); /* "iss": "myapp" */ jwt_set_SET_STR(&jval, "iss", "myapp"); jwt_builder_claim_set(builder, &jval); /* A custom integer claim. */ jwt_set_SET_INT(&jval, "login_count", 42); jwt_builder_claim_set(builder, &jval); ``` -------------------------------- ### JSON backend selection (JSON-C vs Jansson) Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Conditionally links the JSON-C or Jansson library and appends the corresponding JSON source file to JWT_SOURCES based on WITH_JSON_C. ```cmake if (WITH_JSON_C) add_definitions(-DHAVE_JSON_C) target_link_libraries(jwt PUBLIC PkgConfig::JSONC) target_link_libraries(jwt_static PUBLIC PkgConfig::JSONC) list(APPEND JWT_SOURCES libjwt/json-c/jwt-json-c.c) else() target_link_libraries(jwt PUBLIC PkgConfig::JANSSON) target_link_libraries(jwt_static PUBLIC PkgConfig::JANSSON) list(APPEND JWT_SOURCES libjwt/jansson/jwt-jansson.c) endif() ``` -------------------------------- ### Generate preprocessed builder and checker sources for jwt and jwe Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Defines custom commands to preprocess jwt-common.c and jwe-common.c with -DJWT_BUILDER, -DJWT_CHECKER, -DJWE_BUILDER, and -DJWE_CHECKER, producing .i files. These are added as ALL dependencies and linked to both jwt and jwt_static targets. ```cmake add_custom_command( OUTPUT jwt-builder.i COMMAND bash -c "${CMAKE_C_COMPILER} -E -DJWT_BUILDER ${CMAKE_SOURCE_DIR}/libjwt/jwt-common.c -o jwt-builder.i ${CMAKE_C_FLAGS}" -o jwt-builder.i DEPENDS libjwt/jwt-common.c) add_custom_command( OUTPUT jwt-checker.i COMMAND bash -c "${CMAKE_C_COMPILER} -E -DJWT_CHECKER ${CMAKE_SOURCE_DIR}/libjwt/jwt-common.c -o jwt-checker.i ${CMAKE_C_FLAGS}" -o jwt-checker.i DEPENDS libjwt/jwt-common.c) add_custom_command( OUTPUT jwe-builder.i COMMAND bash -c "${CMAKE_C_COMPILER} -E -DJWE_BUILDER ${CMAKE_SOURCE_DIR}/libjwt/jwe-common.c -o jwe-builder.i ${CMAKE_C_FLAGS}" -o jwe-builder.i DEPENDS libjwt/jwe-common.c) add_custom_command( OUTPUT jwe-checker.i COMMAND bash -c "${CMAKE_C_COMPILER} -E -DJWE_CHECKER ${CMAKE_SOURCE_DIR}/libjwt/jwe-common.c -o jwe-checker.i ${CMAKE_C_FLAGS}" -o jwe-checker.i DEPENDS libjwt/jwe-common.c) add_custom_target(gen_jwt_builder ALL DEPENDS jwt-builder.i) add_custom_target(gen_jwt_checker ALL DEPENDS jwt-checker.i) add_custom_target(gen_jwe_builder ALL DEPENDS jwe-builder.i) add_custom_target(gen_jwe_checker ALL DEPENDS jwe-checker.i) add_dependencies(jwt gen_jwt_builder gen_jwt_checker gen_jwe_builder gen_jwe_checker) add_dependencies(jwt_static gen_jwt_builder gen_jwt_checker gen_jwe_builder gen_jwe_checker) ``` -------------------------------- ### Run a single test with ctest Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md Runs a specific test (jwt_builder) with verbose output from the build directory. ```bash ctest -R jwt_builder -V ``` -------------------------------- ### Define jwt_add_test function Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Defines a function to add a test executable from tests/.c, links it to jwt and PkgConfig::CHECK, sets runtime output directory, and adds a test that sources test-env.sh and runs the executable. ```cmake function(jwt_add_test) set(oneValueArgs NAME) cmake_parse_arguments(LibTest "" "${oneValueArgs}" "" ${ARGN}) add_executable(${LibTest_NAME} tests/${LibTest_NAME}.c) target_link_libraries(${LibTest_NAME} PRIVATE jwt) set_target_properties(${LibTest_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests) target_link_libraries(${LibTest_NAME} PRIVATE PkgConfig::CHECK) add_test(NAME ${LibTest_NAME} COMMAND /bin/bash -c "export TEST=${LibTest_NAME}; . ${CMAKE_SOURCE_DIR}/tests/test-env.sh; exec ${CMAKE_BINARY_DIR}/tests/${LibTest_NAME}") endfunction() ``` -------------------------------- ### Verify JPoP proof with embedded JWK (RFC 9578) Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/profiles.dox Sets up a jwt_checker to verify a JPoP proof token. Expects the typ 'openid4vci-proof+jwt', restricts to one algorithm, enables the embedded JWK with a thumbprint pin, and verifies the proof. The key is the confirmed header 'jwk'. ```c jwt_checker_expect_typ(checker, "openid4vci-proof+jwt"); jwt_checker_setalgs(checker, algs, 1); jwt_checker_enable_embedded_jwk(checker, JWK_THUMBPRINT_SHA256, jkt); jwt_checker_verify(checker, proof); /* key is the confirmed header "jwk" */ free(jkt); ``` -------------------------------- ### Set library versioning properties Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Sets the VERSION and SOVERSION properties for the jwt target using variables from configure.ac. ```cmake set_target_properties(jwt PROPERTIES VERSION ${LIBJWT_VERSION_INFO} SOVERSION ${LIBJWT_COMPATVERSION} ) ``` -------------------------------- ### Set pkg-config module names based on enabled backends Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Sets JSON_MODULE_NAME to 'json-c' or 'jansson' based on WITH_JSON_C, and sets OPENSSL_MODULE_NAME, GNUTLS_MODULE_NAME, and MBEDTLS_MODULE_NAME to 'openssl', 'gnutls', and 'mbedcrypto' respectively if the corresponding backend is found. This ensures the pkg-config Requires line only includes libraries actually linked. ```cmake if (WITH_JSON_C) set(JSON_MODULE_NAME "json-c") else() set(JSON_MODULE_NAME "jansson") endif() set(OPENSSL_MODULE_NAME "") set(GNUTLS_MODULE_NAME "") set(MBEDTLS_MODULE_NAME "") if (OPENSSL_FOUND) set(OPENSSL_MODULE_NAME "openssl") endif() if (GNUTLS_FOUND) set(GNUTLS_MODULE_NAME "gnutls") endif() if (MBEDTLS_FOUND) set(MBEDTLS_MODULE_NAME "mbedcrypto") endif() ``` -------------------------------- ### Link libcurl when found Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Adds HAVE_LIBCURL definition and links the libcurl package to both jwt and jwt_static targets when LIBCURL_FOUND is true. ```cmake if (LIBCURL_FOUND) add_definitions(-DHAVE_LIBCURL) target_link_libraries(jwt PUBLIC PkgConfig::LIBCURL) target_link_libraries(jwt_static PUBLIC PkgConfig::LIBCURL) endif() ``` -------------------------------- ### Issue and verify an at+jwt access token (RFC 9068) Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/profiles.dox Sets the typ to 'at+jwt', pins the algorithm to ES256, and requires the mandatory claims (iss, sub, aud, exp, iat, jti, client_id). The verify step uses jwt_checker_expect_typ, jwt_checker_setalgs, jwt_checker_require, and jwt_checker_claim_set to enforce the profile. ```c /* Issue */ jwt_builder_settyp(builder, "at+jwt"); jwt_builder_setkey(builder, JWT_ALG_ES256, signing_key); /* ...set iss/sub/aud/client_id/jti and an exp offset... */ /* Verify */ const char *must[] = { "iss","sub","aud","exp","iat","jti","client_id" }; const jwt_alg_t algs[] = { JWT_ALG_ES256 }; jwt_checker_expect_typ(checker, "at+jwt"); jwt_checker_setalgs(checker, algs, 1); jwt_checker_require(checker, must, 7); jwt_checker_claim_set(checker, JWT_CLAIM_AUD, "https://rs.example"); jwt_checker_setkey(checker, JWT_ALG_ES256, as_key); if (jwt_checker_verify(checker, token) == 0) /* a well-formed RFC 9068 access token */; ``` -------------------------------- ### jwe_builder_new Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Creates a new JWE builder object. ```APIDOC ## jwe_builder_new ### Description Creates a new JWE builder object. ### Returns - **jwe_builder_t *** - A new builder object. ``` -------------------------------- ### Generate a fresh JWK key with jwks_create_generate Source: https://github.com/benmcollins/libjwt/blob/master/README.md Creates a new JWK set with an EC P-256 key for ES256 signing, generating a key ID from the RFC 7638 thumbprint. Supports various key types and backends; unsupported requests return a clean error. ```c jwk_set_t *set = jwks_create_generate(JWK_KEY_TYPE_EC, "P-256", JWT_ALG_ES256, JWK_KEY_GEN_KID); const jwk_item_t *key = jwks_item_get(set, 0); ``` -------------------------------- ### Run tests with valgrind memory checking Source: https://github.com/benmcollins/libjwt/blob/master/CLAUDE.md Runs tests under valgrind memory checking via ctest memcheck. ```bash ctest -T memcheck ``` -------------------------------- ### Generate export header and include directories Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Includes GenerateExportHeader and calls generate_export_header with the optional NO_BUILD_DEPRECATED definition. Adds include directories for source, binary, and libjwt. ```cmake # Must come after the above so headers are available include(GenerateExportHeader) generate_export_header(jwt ${NO_BUILD_DEPRECATED}) include_directories(${CMAKE_SOURCE_DIR}/include ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/libjwt) ``` -------------------------------- ### Enable code coverage option and check dependency Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Defines ENABLE_COVERAGE option (default OFF). If WITH_TESTS is on, requires check>=0.9.10 and finds bats; if coverage is enabled without tests, sends an error. If WITH_TESTS is off and coverage is enabled, sends an error. ```cmake option(ENABLE_COVERAGE "Enable code coverage rules" OFF) # Tests and coverage depend on this, but optional if (WITH_TESTS) if (ENABLE_COVERAGE) set(CHECK_REQUIRED REQUIRED) endif() pkg_check_modules(CHECK check>=0.9.10 IMPORTED_TARGET ${CHECK_REQUIRED}) find_program (BATS_CMD bats) else() if (ENABLE_COVERAGE) message(SEND_ERROR "You must set WITH_TESTS=ON to enable code coverage") endif() endif() ``` -------------------------------- ### Encrypt a JWE token with direct key management and A256GCM Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Creates a JWE token using the 'dir' key management algorithm and A256GCM content encryption. Loads a JWK set from a file, retrieves the first key, and generates a token with an explicit length. ```c #include #include #include jwe_builder_t *builder = NULL; jwk_set_t *keys = NULL; const jwk_item_t *key = NULL; const char *message = "the launch code is 0000"; char *token = NULL; keys = jwks_create_fromfile("oct_dir_256.json"); key = jwks_item_get(keys, 0); builder = jwe_builder_new(); jwe_builder_setkey(builder, JWE_ALG_DIR, JWE_ENC_A256GCM, key); ``` -------------------------------- ### jwe_builder_setkey Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Sets the key management and content encryption algorithms along with the key for JWE encryption. ```APIDOC ## jwe_builder_setkey ### Description Sets the key management and content encryption algorithms along with the key for JWE encryption. ### Parameters - **builder** (jwe_builder_t *) - Required - The builder object. - **alg** (jwe_key_alg_t) - Required - The key management algorithm (e.g., JWE_ALG_DIR). - **enc** (jwe_enc_t) - Required - The content encryption algorithm (e.g., JWE_ENC_A256GCM). - **key** (const jwk_item_t *) - Required - The key to use. ### Example ```c jwe_builder_setkey(builder, JWE_ALG_DIR, JWE_ENC_A256GCM, key); ``` ``` -------------------------------- ### Optional dependency detection for GnuTLS, MbedTLS, libcurl, kcapi, and OpenSSL Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Conditionally checks for optional crypto and utility libraries using pkg_check_modules or find_library. GnuTLS requires version >= 3.8.8, MbedTLS >= 3.6.0, libcurl >= 7.8.8, and OpenSSL >= 3.0.0. The GNUTLS_AUTO option controls whether GnuTLS is required. ```cmake # Optional if (WITH_GNUTLS) if (NOT GNUTLS_AUTO) set(GNUTLS_REQUIRED REQUIRED) endif() pkg_check_modules(GNUTLS gnutls>=3.8.8 IMPORTED_TARGET ${GNUTLS_REQUIRED}) endif() if (WITH_MBEDTLS) pkg_check_modules(MBEDTLS mbedcrypto>=3.6.0 IMPORTED_TARGET REQUIRED) endif() if (WITH_LIBCURL) pkg_check_modules(LIBCURL libcurl>=7.8.8 IMPORTED_TARGET REQUIRED) endif() if (WITH_KCAPI_MD) find_library(HAVE_KCAPI kcapi REQUIRED) endif() # Optional (default ON). OpenSSL was historically mandatory; it is now one of # the interchangeable crypto backends, like GnuTLS and MbedTLS. if (WITH_OPENSSL) pkg_check_modules(OPENSSL openssl>=3.0.0 IMPORTED_TARGET REQUIRED) endif() ``` -------------------------------- ### Build LibJWT with CMake Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/mainpage.dox Build LibJWT from source using CMake. Requires Check (>= 0.9.10) for unit testing and Doxygen (>= 1.13.0) for documentation. ```sh $ mkdir build $ cd build $ cmake .. $ make ``` -------------------------------- ### List JWT_SOURCES source files Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Defines the JWT_SOURCES variable with all libjwt source files, including memory, core, JWKS, set/get, crypto ops, encode/verify, builder/checker, JWE, and curl support. ```cmake set(JWT_SOURCES libjwt/jwt-memory.c libjwt/jwt.c libjwt/jwks.c libjwt/jwt-setget.c libjwt/jwt-crypto-ops.c libjwt/jwt-encode.c libjwt/jwt-verify.c libjwt/jwt-builder.c libjwt/jwt-checker.c libjwt/jwe-setget.c libjwt/jwe.c libjwt/jwe-builder.c libjwt/jwe-checker.c libjwt/jwks-curl.c libjwt/jwk-export.c) ``` -------------------------------- ### Build pkg-config linker flags Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Constructs LIBJWT_LDFLAGS by concatenating linker flags from the selected JSON library and other dependencies. ```cmake unset(LIBJWT_LDFLAGS) if (WITH_JSON_C) set(_JSON_LDFLAGS ${JSONC_LDFLAGS}) else() set(_JSON_LDFLAGS ${JANSSON_LDFLAGS}) endif() foreach (FLAG ${_JSON_LDFLAGS} ${OPENSSL_LDFLAGS} ${GNUTLS_LDFLAGS} ${MBEDTLS_LDFLAGS} ${LIBCURL_LDFLAGS}) string(APPEND LIBJWT_LDFLAGS " " ${FLAG}) endforeach() ``` -------------------------------- ### Define shared and static library targets for jwt Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt Creates shared and static libraries named jwt and jwt_static. The static library sets OUTPUT_NAME to jwt and defines JWT_STATIC_DEFINE. If HAVE_KCAPI is set, links kcapi and defines USE_KCAPI_MD. ```cmake add_library(jwt SHARED) add_library(jwt_static STATIC) set_target_properties(jwt_static PROPERTIES OUTPUT_NAME jwt COMPILE_FLAGS -DJWT_STATIC_DEFINE) if (HAVE_KCAPI) target_link_libraries(jwt PRIVATE kcapi) target_link_libraries(jwt_static PRIVATE kcapi) add_definitions(-DUSE_KCAPI_MD) endif() ``` -------------------------------- ### jwe-encrypt -k KEY -a ALG -e ENC [options] Source: https://github.com/benmcollins/libjwt/blob/master/tools/jwe-encrypt.1.md Encrypts content into a JWE token. Requires a recipient JWK file, a key management algorithm, and a content encryption algorithm. The plaintext is taken from the -j option or standard input, and the token is written to standard output. ```APIDOC ## jwe-encrypt -k KEY -a ALG -e ENC [options] ### Description Encrypts content into a JWE token. Requires a recipient JWK file, a key management algorithm, and a content encryption algorithm. The plaintext is taken from the -j option or standard input, and the token is written to standard output. ### Method CLI ### Endpoint jwe-encrypt ### Parameters #### Options - **-h, --help** - Optional - Show help and exit. - **-k, --key=_FILE_** - Required - File containing the recipient JSON Web Key. - **-a, --algorithm=_ALG_** - Required - The JWE key management algorithm. One of: **dir**, **A128KW**, **A192KW**, **A256KW**, **RSA-OAEP**, **RSA-OAEP-256**, **ECDH-ES**, **ECDH-ES+A128KW**, **ECDH-ES+A192KW**, **ECDH-ES+A256KW**. - **-e, --enc=_ENC_** - Required - The JWE content encryption algorithm. One of: **A128GCM**, **A192GCM**, **A256GCM**, **A128CBC-HS256**, **A192CBC-HS384**, **A256CBC-HS512**. - **-f, --format=_FORMAT_** - Optional - The serialization to produce: **compact** (default), **json-flat**, or **json-general**. Compact and Flattened forms carry exactly one recipient. - **-r, --recipient=_ALG_:_FILE_** - Optional - Add another recipient: key management algorithm _ALG_ with the JWK in _FILE_. May be given more than once. Using **-r** implies **--format=json-general**. **dir** and **ECDH-ES** cannot be combined with other recipients. - **-A, --aad=_FILE_** - Optional - File whose raw contents become the JWE Additional Authenticated Data (the **aad** member). Only available in JSON serializations. - **-j, --json=_STRING_** - Optional - The plaintext to encrypt. If omitted, the plaintext is read from standard input. ### Request Example ``` jwe-encrypt -k recipient.jwk -a RSA-OAEP -e A256GCM -j '{"sub":"1234567890"}' ``` ### Response #### Success Response - The resulting JWE token is written to standard output. #### Response Example ``` eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ... ``` ### Notes - For **dir**, the JWK must be a symmetric (**oct**) key whose length exactly matches the CEK length required by the **enc** algorithm. - For **A*KW**, the JWK must be an **oct** key of the matching size. - For **RSA-OAEP** and **RSA-OAEP-256**, the JWK must be an RSA public (or private) key. - For **ECDH-ES** and its **+A*KW** variants, the JWK must be an EC key (P-256/384/521) or an OKP X-curve key (X25519/X448). - The key must permit encryption use: a key marked **"use":"sig"** or whose **key_ops** forbid the operation is rejected. - For JSON serializations, the same header parameter name must not appear in more than one of the protected, shared-unprotected, or per-recipient headers. ``` -------------------------------- ### JSON serialization with AAD using jwe_builder_set_format and jwe_builder_set_aad Source: https://github.com/benmcollins/libjwt/blob/master/doxygen/examples.dox Produces the Flattened JSON Serialization with Additional Authenticated Data (AAD). AAD is authenticated but not encrypted. The builder is configured with a symmetric key and the JSON format is selected. ```c static const unsigned char aad[] = "context-id:42"; builder = jwe_builder_new(); jwe_builder_setkey(builder, JWE_ALG_DIR, JWE_ENC_A256GCM, key); /* Produce the Flattened JSON Serialization with AAD. */ jwe_builder_set_format(builder, JWE_FORMAT_JSON_FLAT); jwe_builder_set_aad(builder, aad, sizeof(aad) - 1); token = jwe_builder_generate(builder, (const unsigned char *)message, strlen(message)); ``` -------------------------------- ### Add unit tests and coverage targets Source: https://github.com/benmcollins/libjwt/blob/master/CMakeLists.txt If CHECK_FOUND, includes CTest, defines a list of unit tests, adds them via jwt_add_test, adds a CLI test if bats is found, creates a 'check' target, and optionally sets up code coverage with lcov. If coverage is enabled but check is not found, sends an error. ```cmake if (CHECK_FOUND) include(CTest) set (UNIT_TESTS jwt_crypto) # JWKS Tests list (APPEND UNIT_TESTS jwt_jwks jwt_jwks_errors jwt_ec jwt_rsa jwt_hs jwt_jwks_pem jwt_thumbprint) # Checker and Builder list (APPEND UNIT_TESTS jwt_builder jwt_checker jwt_flipflop jwt_xbackend) # JWS JSON Serialization (multi-signature) list (APPEND UNIT_TESTS jws_json) # RFC 7797 unencoded / detached payload list (APPEND UNIT_TESTS jws_b64) # RFC 8725 typ helper + algorithm allowlist list (APPEND UNIT_TESTS jwt_typ_alg) # Key generation (jwks_generate) list (APPEND UNIT_TESTS jwt_generate) # RFC 7517 X.509 params (x5c/x5t/x5t#S256) list (APPEND UNIT_TESTS jwt_x509) # Cached remote JWKS source (TTL/ETag/cooldown) list (APPEND UNIT_TESTS jwt_jwks_cache) # Application profiles (#317): the small primitives + worked recipes list (APPEND UNIT_TESTS jwt_hash jwt_require jwt_embedded_jwk jwt_profiles) # ML-DSA (FIPS 204 / RFC 9964). The test is a no-op unless the build # enabled WITH_ML_DSA against a capable backend. list (APPEND UNIT_TESTS jwt_mldsa) # JWE list (APPEND UNIT_TESTS jwe_foundation jwe_keys jwe_gcm jwe_cbc jwe_aeskw jwe_gcmkw jwe_pbes2 jwe_rsa jwe_ecdh jwe_json jwe_aad jwe_multi jwe_json_neg) # Claims list (APPEND UNIT_TESTS jwt_claims jwt_cnf) # Security list (APPEND UNIT_TESTS jwt_security jwt_alg_downgrade) foreach (TEST ${UNIT_TESTS}) jwt_add_test(NAME ${TEST}) endforeach() if (BATS_CMD) add_test(NAME jwt_cli COMMAND /bin/bash -c "export SRCDIR=\"${CMAKE_SOURCE_DIR}\"; \"${CMAKE_SOURCE_DIR}\"/tests/jwt-cli.bats") endif() add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND} DEPENDS ${UNIT_TESTS} ${TOOLS}) if (ENABLE_COVERAGE) set(CMAKE_BUILD_TYPE "Debug") include(CodeCoverage) append_coverage_compiler_flags() set(COVERAGE_LCOV_INCLUDES "${CMAKE_SOURCE_DIR}/libjwt/" "${CMAKE_SOURCE_DIR}/tools/") setup_target_for_coverage_lcov( NAME check-code-coverage OUTPUT "${PROJECT_NAME}-${PROJECT_VERSION}-coverage" TITLE "${PROJECT_NAME}-${PROJECT_VERSION} Code Coverage" EXECUTABLE ctest -j ${PROCESSOR_COUNT} DEPENDENCIES ${UNIT_TESTS} ${TOOLS}) endif() elseif(ENABLE_COVERAGE) message(SEND_ERROR "Coverage enabled, but did not find check library") endif() ```