### Basic CMake Installation Source: https://github.com/thalhammer/jwt-cpp/blob/master/docs/install.md Steps to configure, build, and install JWT-CPP using CMake. Ensure OpenSSL is installed beforehand. ```sh cmake . cmake --build . # Make sure everything compiles and links together cmake --install . ``` -------------------------------- ### Build ES256K Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for ES256K signing. ```cmake add_executable(es256k es256k.cpp) target_link_libraries(es256k jwt-cpp::jwt-cpp) ``` -------------------------------- ### Build and Run RSA Create Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for RSA key creation and a custom target to run it. ```cmake add_executable(rsa-create rsa-create.cpp) target_link_libraries(rsa-create jwt-cpp::jwt-cpp) add_custom_target(rsa-create-run COMMAND rsa-create) ``` -------------------------------- ### Build and Run Print Claims Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for printing claims and a custom target to run it. ```cmake add_executable(print-claims print-claims.cpp) target_link_libraries(print-claims jwt-cpp::jwt-cpp) add_custom_target(print-claims-run COMMAND print-claims) ``` -------------------------------- ### Build and Run RSA Verify Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for RSA signature verification and a custom target to run it. ```cmake add_executable(rsa-verify rsa-verify.cpp) target_link_libraries(rsa-verify jwt-cpp::jwt-cpp) add_custom_target(rsa-verify-run COMMAND rsa-verify) ``` -------------------------------- ### None Algorithm Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Demonstrates creating a JWT with the 'none' algorithm and verifying it. The 'none' algorithm is not recommended for production environments. ```cpp auto token = jwt::create() .set_type("JWT") .sign(jwt::algorithm::none{}); jwt::verify() .allow_algorithm(jwt::algorithm::none{}) .verify(decoded); ``` -------------------------------- ### Build and Run JWKS Verify Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for JWKS verification and a custom target to run it. ```cmake add_executable(jwks-verify jwks-verify.cpp) target_link_libraries(jwks-verify jwt-cpp::jwt-cpp) add_custom_target(jwks-verify-run COMMAND jwks-verify) ``` -------------------------------- ### Build Partial Claim Verifier Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for partial claim verification, linking against jwt-cpp and nlohmann_json. ```cmake add_executable(partial-claim-verifier partial-claim-verifier.cpp) target_link_libraries(partial-claim-verifier jwt-cpp::jwt-cpp nlohmann_json::nlohmann_json) ``` -------------------------------- ### Build and Run Private Claims Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Defines an executable for handling private claims and a custom target to run it. ```cmake add_executable(private-claims private-claims.cpp) target_link_libraries(private-claims jwt-cpp::jwt-cpp) add_custom_target(private-claims-run COMMAND private-claims) ``` -------------------------------- ### JWT Creation, Signing, and Decoding Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/types.md Demonstrates creating a JWT, setting issuer and expiration, adding custom payload claims, signing it with HS256, decoding it, and accessing standard and custom claims. ```cpp #include #include #include int main() { auto token = jwt::create() .set_issuer("myapp") .set_expires_in(std::chrono::hours{1}) .set_payload_claim("user_id", jwt::claim(int64_t(123))) .set_payload_claim("email", jwt::claim(std::string("user@example.com"))) .sign(jwt::algorithm::hs256{"secret"}); auto decoded = jwt::decode(token); // Access standard claims (return jwt::date) auto iat = decoded.get_issued_at(); auto exp = decoded.get_expires_at(); std::time_t exp_time = std::chrono::system_clock::to_time_t(exp); std::cout << "Expires: " << std::put_time(std::localtime(&exp_time), "%Y-%m-%d %H:%M:%S") << "\n"; // Access custom claims (check type first) auto user_id_claim = decoded.get_payload_claim("user_id"); if (user_id_claim.get_type() == jwt::json::type::integer) { std::cout << "User ID: " << user_id_claim.as_integer() << "\n"; } auto email_claim = decoded.get_payload_claim("email"); if (email_claim.get_type() == jwt::json::type::string) { std::cout << "Email: " << email_claim.as_string() << "\n"; } } ``` -------------------------------- ### Example: Creating Claims from Different Types Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/basic-claim.md Demonstrates how to create `basic_claim` objects from various C++ types like strings, dates, integers, booleans, and arrays. ```APIDOC ## Examples ### Creating Claims from Different Types ```cpp #include #include int main() { // String claim auto string_claim = jwt::claim(std::string("value")); // Date claim auto now = std::chrono::system_clock::now(); auto date_claim = jwt::claim(now); // Integer claim auto int_claim = jwt::claim(int64_t(123)); // Boolean claim auto bool_claim = jwt::claim(true); // Array claim from vector std::vector tags{"admin", "user"}; auto array_claim = jwt::claim(tags.begin(), tags.end()); } ``` ``` -------------------------------- ### Configure CMake with wolfSSL Source: https://github.com/thalhammer/jwt-cpp/blob/master/docs/ssl.md Use this command to configure the build system to use the wolfSSL library. Ensure wolfSSL is installed on your system. ```sh cmake . -DJWT_SSL_LIBRARY:STRING=wolfSSL ``` -------------------------------- ### HMAC Algorithm Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Shows how to create a JWT using the HS256 algorithm with a shared secret key and how to verify it. Ensure the same secret key is used for both signing and verification. ```cpp // Create token auto token = jwt::create() .set_type("JWT") .set_issuer("auth0") .sign(jwt::algorithm::hs256{"my-secret-key"}); // Verify token jwt::verify() .allow_algorithm(jwt::algorithm::hs256{"my-secret-key"}) .verify(decoded); ``` -------------------------------- ### RSA Algorithm Example Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Demonstrates creating a JWT using the RS256 algorithm with a private key and verifying it using a public key. The private key is used for signing, while the public key is used for verification. ```cpp #include #include std::string read_file(const std::string& path) { std::ifstream f(path); std::stringstream buf; buf << f.rdbuf(); return buf.str(); } int main() { std::string private_key = read_file("private.pem"); std::string public_key = read_file("public.pem"); // Create with private key for signing auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::rs256{public_key, private_key}); // Verify with public key only jwt::verify() .allow_algorithm(jwt::algorithm::rs256{public_key, ""}) .verify(decoded); } ``` -------------------------------- ### Basic CMakeLists.txt for jwt-cpp Source: https://github.com/thalhammer/jwt-cpp/blob/master/tests/cmake/CMakeLists.txt This snippet shows a minimal CMakeLists.txt file to find and link the jwt-cpp library. Ensure you have jwt-cpp installed and configured for CMake to find it. ```cmake cmake_minimum_required(VERSION 3.14) project(jwt-cpp-installation-tests) set(TEST CACHE STRING "The test source file to be used") find_package(jwt-cpp 0.7.2 EXACT REQUIRED CONFIG) add_executable(test-project ${TEST}.cpp) target_link_libraries(test-project jwt-cpp::jwt-cpp) ``` -------------------------------- ### Get Algorithm from Header Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Retrieves the 'alg' (algorithm) header claim. This is a convenience method for accessing the algorithm used for signing. ```cpp std::string get_algorithm() const ``` -------------------------------- ### CMake FetchContent Integration Source: https://github.com/thalhammer/jwt-cpp/blob/master/docs/install.md Using CMake's FetchContent module to download and build JWT-CPP directly within your project's build tree. This example pins to a specific Git tag. ```cmake include(FetchContent) fetchcontent_declare(jwt-cpp GIT_REPOSITORY https://github.com/Thalhammer/jwt-cpp.git GIT_TAG 08bcf77a687fb06e34138e9e9fa12a4ecbe12332 # v0.7.0 release ) set(JWT_BUILD_EXAMPLES OFF CACHE BOOL "disable building examples" FORCE) fetchcontent_makeavailable(jwt-cpp) target_link_libraries(my_app PRIVATE jwt-cpp::jwt-cpp) ``` -------------------------------- ### PSS PS256 Token Creation and Verification Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Example of creating a JWT signed with PS256 and then verifying it. Assumes PEM-encoded RSA keys are available. ```cpp std::string private_key = read_file("private_rsa.pem"); std::string public_key = read_file("public_rsa.pem"); auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::ps256{public_key, private_key}); jwt::verify() .allow_algorithm(jwt::algorithm::ps256{public_key, ""}) .verify(decoded); ``` -------------------------------- ### Add Executable and Link jwt-cpp Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/configuration.md This snippet shows how to define your application executable and link it against the jwt-cpp library using CMake. Ensure jwt-cpp is installed or available in your build environment. ```cmake add_executable(my_app main.cpp) target_link_libraries(my_app PRIVATE jwt-cpp) ``` -------------------------------- ### ECDSA ES256 Token Creation and Verification Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Example of creating a JWT signed with ES256 and then verifying it. Assumes PEM-encoded keys are available. ```cpp std::string private_key = read_file("ec_private.pem"); std::string public_key = read_file("ec_public.pem"); // Create token auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::es256{public_key, private_key}); // Verify token jwt::verify() .allow_algorithm(jwt::algorithm::es256{public_key, ""}) .verify(decoded); ``` -------------------------------- ### EdDSA Ed25519 Token Creation and Verification Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Example of creating a JWT signed with Ed25519 and then verifying it. Assumes PEM-encoded keys are available. ```cpp std::string private_key = read_file("ed25519_private.pem"); std::string public_key = read_file("ed25519_public.pem"); auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::ed25519{public_key, private_key}); jwt::verify() .allow_algorithm(jwt::algorithm::ed25519{public_key, ""}) .verify(decoded); ``` -------------------------------- ### Get Public Key Use Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves the 'use' (public key use) parameter from a JWK. This specifies the intended use of the key, such as 'sig' for signing or 'enc' for encryption. ```cpp typename json_traits::string_type get_use() const ``` -------------------------------- ### PicoJSON Dependency Check Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Checks if PicoJSON is disabled. If it is, the build fails as examples require it. ```cmake if(JWT_DISABLE_PICOJSON) message(FATAL_ERROR "examples require picojson to be available!") endif() ``` -------------------------------- ### Linking JWT-CPP in a CMake Project Source: https://github.com/thalhammer/jwt-cpp/blob/master/docs/install.md How to find and link the JWT-CPP library in your own CMake project after installation. ```cmake find_package(jwt-cpp CONFIG REQUIRED) target_link_libraries(my_app PRIVATE jwt-cpp::jwt-cpp) ``` -------------------------------- ### Algorithm Agility with Fallback Creation Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Create a token using ES256, and if an exception occurs, fall back to creating the token using RS256. This demonstrates dynamic algorithm selection during token signing. ```cpp std::string token; try { token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::es256{pub_ec, priv_ec}); } catch (const std::exception& e) { // Fallback to RSA if EC fails token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::rs256{pub_rsa, priv_rsa}); } ``` -------------------------------- ### Get JWT Signature Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Retrieve the raw signature bytes and the base64url encoded signature from a decoded JWT. ```cpp #include int main() { auto decoded = jwt::decode(token); // Get signature in both forms const auto& sig_raw = decoded.get_signature(); const auto& sig_b64 = decoded.get_signature_base64(); std::cout << "Signature length: " << sig_raw.length() << " bytes\n"; std::cout << "Signature (base64url): " << sig_b64 << "\n"; // Use signature for verification (done by verifier) } ``` -------------------------------- ### Get Original Token String Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the original, unmodified JWT token string that was passed to the constructor. ```cpp const typename json_traits::string_type& get_token() const noexcept ``` -------------------------------- ### Create and Sign a Token with Expiration Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/create-builder.md Shows how to create a token with standard expiration claims (issued at, not before, expires at) and sign it using the HS256 algorithm. ```cpp #include #include int main() { auto now = jwt::date::clock::now(); auto token = jwt::create() .set_issued_at(now) .set_not_before(now) .set_expires_at(now + std::chrono::hours{1}) .set_issuer("my-service") .set_audience("my-app") .sign(jwt::algorithm::hs256{"my-secret-key"}); std::cout << "Token: " << token << "\n"; } ``` -------------------------------- ### Get All Keys from JWKS Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves all the JWK objects contained within a JWKS object. Use this to iterate over a set of keys. ```cpp const std::vector>& get_keys() const ``` -------------------------------- ### Get Algorithm Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves the 'alg' (algorithm) parameter from a JWK. This specifies the algorithm intended for use with the key (e.g., RS256). ```cpp typename json_traits::string_type get_algorithm() const ``` -------------------------------- ### Compile with CMake Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/README.md Standard compilation process using CMake. Creates a build directory and then builds the project. ```bash mkdir build cd build cmake .. cmake --build . ``` -------------------------------- ### Create and Sign an RSA Token with Custom Claims Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/create-builder.md Demonstrates signing a token using the RS256 algorithm with an RSA private key. It includes setting a key ID, issuer, subject, audience, and custom claims like email and roles. ```cpp #include #include #include std::string read_file(const std::string& filename) { std::ifstream file(filename); std::stringstream buffer; buffer << file.rdbuf(); return buffer.str(); } int main() { std::string private_key = read_file("private.pem"); auto token = jwt::create() .set_type("JWT") .set_key_id("rsa-key-1") .set_issuer("iss.example.com") .set_subject("sub.example.com") .set_audience("aud.example.com") .set_payload_claim("email", jwt::claim(std::string("user@example.com"))) .set_payload_claim("roles", jwt::claim( std::vector{"admin", "user"} )) .sign(jwt::algorithm::rs256{private_key, ""}); std::cout << "Token: " << token << "\n"; } ``` -------------------------------- ### Get Decoded Signature Bytes Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the decoded signature component as raw binary data. This is the Base64url decoded signature. ```cpp const typename json_traits::string_type& get_signature() const noexcept ``` -------------------------------- ### Get Payload Component in Base64url Encoding Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the payload component in its original Base64url encoded form, without padding. ```cpp const typename json_traits::string_type& get_payload_base64() const noexcept ``` -------------------------------- ### Basic CMake Configuration Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/CMakeLists.txt Sets the minimum CMake version and project name. Finds the jwt-cpp package and adds a subdirectory for traits. ```cmake cmake_minimum_required(VERSION 3.14) project(jwt-cpp-examples) if(NOT TARGET jwt-cpp) find_package(jwt-cpp CONFIG REQUIRED) endif() add_subdirectory(traits) ``` -------------------------------- ### Get Decoded Payload JSON String Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the decoded payload component as a JSON string. This is the Base64url decoded payload. ```cpp const typename json_traits::string_type& get_payload() const noexcept ``` -------------------------------- ### Sign a Token with a Custom Algorithm Source: https://github.com/thalhammer/jwt-cpp/blob/master/docs/signing.md Create a JWT token and sign it using your custom algorithm implementation. Ensure your algorithm is instantiated correctly. ```cpp auto token = jwt::create() .set_id("custom-algo-example") .set_issued_now() .set_expires_in(std::chrono::seconds{36000}) .set_payload_claim("sample", jwt::claim(std::string{"test"})) .sign(your_algorithm{/* what ever you want */}); ``` -------------------------------- ### Get Header Component in Base64url Encoding Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the header component in its original Base64url encoded form, without padding. ```cpp const typename json_traits::string_type& get_header_base64() const noexcept ``` -------------------------------- ### Create and Sign a JWT Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/README.md Demonstrates how to create a new JWT, set standard claims like issuer, subject, and expiration, add custom payload claims, and sign it using the HS256 algorithm. ```cpp #include auto token = jwt::create() .set_issuer("myapp") .set_subject("user123") .set_audience("api.example.com") .set_expires_in(std::chrono::hours{24}) .set_payload_claim("email", jwt::claim(std::string("user@example.com"))) .sign(jwt::algorithm::hs256{"my-secret-key"}); std::cout << "Token: " << token << "\n"; ``` -------------------------------- ### Get Decoded Header JSON String Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the decoded header component as a JSON string. This is the Base64url decoded header. ```cpp const typename json_traits::string_type& get_header() const noexcept ``` -------------------------------- ### Create JWT with Various Claim Types Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/basic-claim.md Demonstrates how to create a JWT and set various payload claims including string, integer, boolean, and string array types. ```cpp #include int main() { auto token = jwt::create() .set_issuer("myapp") .set_subject("user123") .set_payload_claim("email", jwt::claim(std::string("user@example.com"))) .set_payload_claim("age", jwt::claim(int64_t(25))) .set_payload_claim("active", jwt::claim(true)) .set_payload_claim("tags", jwt::claim(std::vector{"admin", "moderator"})) .sign(jwt::algorithm::hs256{"secret"}); } ``` -------------------------------- ### Using Custom JSON Traits with nlohmann/json Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/types.md Shows how to integrate a custom JSON library, specifically nlohmann/json, by including the appropriate traits header and using it to create and decode JWTs. ```cpp #include using traits = jwt::traits::nlohmann_json; auto token = jwt::create() .set_issuer("auth0") .sign(jwt::algorithm::hs256{"secret"}); auto decoded = jwt::decode(token); ``` -------------------------------- ### Reusable Verifier Configuration Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/verify-verifier.md Demonstrates creating a verifier once and reusing it for multiple tokens. This is efficient for high-throughput scenarios. Verification results are reported using std::error_code. ```cpp #include int main() { // Create once, use many times auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs256{"secret"}) .with_issuer("auth0") .with_audience("api.example.com") .leeway(5); for (const auto& token : incoming_tokens) { auto decoded = jwt::decode(token); std::error_code ec; verifier.verify(decoded, ec); if (!ec) { std::cout << "Token valid: " << token << "\n"; } } } ``` -------------------------------- ### Get Key Operations Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves the 'key_ops' (key operations) parameter from a JWK as a set of strings. This defines the permitted cryptographic operations for the key. ```cpp typename basic_claim_t::set_t get_key_operations() const ``` -------------------------------- ### Create and Sign a Simple HMAC Token Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/create-builder.md Demonstrates creating a JWS token with basic claims (type, issuer, subject, custom payload) and signing it using the HS256 algorithm with a secret key. ```cpp #include #include int main() { auto token = jwt::create() .set_type("JWS") .set_issuer("auth0") .set_subject("user123") .set_payload_claim("custom", jwt::claim(std::string("data"))) .sign(jwt::algorithm::hs256{"secret"}); std::cout << "Token: " << token << "\n"; } ``` -------------------------------- ### Get Key Type Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves the 'kty' (key type) parameter from a JWK. This indicates the type of cryptographic key (e.g., RSA, EC). ```cpp typename json_traits::string_type get_key_type() const ``` -------------------------------- ### Create JWT Builder Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/README.md Initializes a token builder for creating and signing JWTs. Supports default clock and JSON traits. ```cpp template builder create(); ``` -------------------------------- ### Get JWK Claim Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves any JWK claim by its name. Use this for specific key parameters like 'n', 'e', 'k', 'crv', etc. ```cpp basic_claim_t get_jwk_claim(const typename json_traits::string_type& name) const ``` -------------------------------- ### Get Signature Component in Base64url Encoding Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Returns the signature component in its original Base64url encoded form. This includes padding if present in the original token. ```cpp const typename json_traits::string_type& get_signature_base64() const noexcept ``` -------------------------------- ### Find Key by Key ID and Verify Token Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Fetches JWKS, decodes a token, extracts the 'kid' from the token header, finds the corresponding key in the JWKS, and verifies the token using the extracted key. ```cpp #include int main() { // Get JWKS from remote endpoint auto jwks_json = fetch_jwks("https://auth.example.com/.well-known/jwks.json"); auto jwks = jwt::parse_jwks(jwks_json); // Decode token auto decoded = jwt::decode(token); // Get key ID from token header auto kid = decoded.get_header_claim("kid").as_string(); // Find matching key in JWKS try { auto key = jwks.get_key(kid); std::cout << "Found key: " << kid << "\n"; std::cout << "Algorithm: " << key.get_algorithm() << "\n"; // Construct RSA public key from JWK auto n = key.get_jwk_claim("n").as_string(); auto e = key.get_jwk_claim("e").as_string(); // Decode base64url to construct PEM std::string public_key = construct_rsa_public_key(n, e); // Verify token jwt::verify() .allow_algorithm(jwt::algorithm::rs256{public_key, ""}) .with_issuer("https://auth.example.com") .verify(decoded); std::cout << "Token verified!\n"; } catch (const std::runtime_error& e) { std::cerr << "Key not found: " << e.what() << "\n"; } } ``` -------------------------------- ### Basic CMakeLists.txt for JWT-CPP Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/configuration.md A minimal CMakeLists.txt file to set up a C++ project using JWT-CPP as a header-only library. It includes OpenSSL and JWT-CPP headers and links them to the executable. ```cmake cmake_minimum_required(VERSION 3.10) project(MyJWTApp) set(CMAKE_CXX_STANDARD 17) # Find OpenSSL find_package(OpenSSL REQUIRED) # JWT-CPP (header-only) add_library(jwt-cpp INTERFACE) target_include_directories(jwt-cpp INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include ) target_link_libraries(jwt-cpp INTERFACE OpenSSL::Crypto OpenSSL::SSL) # Your application add_executable(my_app main.cpp) target_link_libraries(my_app PRIVATE jwt-cpp) ``` -------------------------------- ### Parse JWKS from OpenID Connect Provider Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Fetches a JWKS from a given URL (simulated by fetch_jwks) and parses it. It then iterates through the keys to print their Key IDs (kid). ```cpp #include #include // Pseudo-code for fetching JWKS from OIDC provider std::string fetch_jwks(const std::string& url); int main() { // Fetch JWKS from standard location std::string jwks_json = fetch_jwks("https://auth.example.com/.well-known/jwks.json"); auto jwks = jwt::parse_jwks(jwks_json); auto keys = jwks.get_keys(); std::cout << "JWKS contains " << keys.size() << " keys\n"; // Print all key IDs for (const auto& key : keys) { if (key.has_jwk_claim("kid")) { auto kid = key.get_jwk_claim("kid").as_string(); std::cout << "Key ID: " << kid << "\n"; } } } ``` -------------------------------- ### Build with jsoncpp Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/traits/CMakeLists.txt Configures a CMake executable to link jwt-cpp with jsoncpp_static. Requires jsoncpp to be found via find_package. ```cmake find_package(jsoncpp CONFIG) if(TARGET jsoncpp_static) add_executable(open-source-parsers-jsoncpp open-source-parsers-jsoncpp.cpp) target_link_libraries(open-source-parsers-jsoncpp jsoncpp_static jwt-cpp::jwt-cpp) endif() ``` -------------------------------- ### Build with kazuho-picojson Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/traits/CMakeLists.txt Configures a CMake executable to link jwt-cpp with kazuho-picojson using a private find module. Requires the find-kazuho-picojson.cmake script. ```cmake include("../../cmake/private-find-kazuho-picojson.cmake") if(TARGET kazuho_picojson) add_executable(kazuho-picojson kazuho-picojson.cpp) target_link_libraries(kazuho-picojson jwt-cpp::jwt-cpp kazuho_picojson) endif() ``` -------------------------------- ### Get Specific Header Claim Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Retrieves a specific header claim by its name (e.g., 'alg', 'typ', 'kid'). Throws jwt::error::claim_not_present_exception if the claim does not exist. ```cpp basic_claim_t get_header_claim(const typename json_traits::string_type& name) const ``` -------------------------------- ### Multiple Algorithms with Fallback Verification Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md Configure a verifier to accept tokens signed with RS256, ES256, or HS256. The verifier will attempt to verify the token using each allowed algorithm. ```cpp auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::rs256{public_key_rs, ""}) .allow_algorithm(jwt::algorithm::es256{public_key_ec, ""}) .allow_algorithm(jwt::algorithm::hs256{"shared_secret"}); verifier.verify(decoded); // Accepts any of the three ``` -------------------------------- ### jwks::get_keys Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/jwk-jwks.md Retrieves all the JWK objects contained within a JWKS object. This method is fundamental for iterating through a set of keys, for example, to find a specific key for verification. ```APIDOC ## jwks::get_keys ### Description Returns all keys in the JWKS set. ### Signature ```cpp const std::vector>& get_keys() const ``` ### Returns Vector of `jwk` objects representing all keys in the set. ``` -------------------------------- ### Create and Sign a JWT Token Source: https://github.com/thalhammer/jwt-cpp/blob/master/README.md Create a JWT token, set its type, issuer, and payload claim, and then sign it with a secret. ```cpp auto token = jwt::create() .set_type("JWS") .set_issuer("auth0") .set_payload_claim("sample", jwt::claim(std::string("test"))) .sign(jwt::algorithm::hs256{"secret"}); ``` -------------------------------- ### Manual JWT Encoding Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/base64-utilities.md Demonstrates manual JWT encoding by manually creating header and payload JSON, encoding them to Base64URL, and then signing and concatenating the parts. This is typically handled by the `create().sign()` method. ```cpp #include int main() { // Manual JWT encoding (normally handled by create().sign()) // 1. Create header JSON std::string header_json = R"({\"alg\":\"HS256\",\"typ\":\"JWT\"})"; // 2. Create payload JSON std::string payload_json = R"({\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022})"; // 3. Encode header and payload auto header_b64 = jwt::base::trim( jwt::base::encode(header_json) ); auto payload_b64 = jwt::base::trim( jwt::base::encode(payload_json) ); // 4. Create signing input std::string signing_input = header_b64 + "." + payload_b64; // 5. Sign (using HMAC) std::string secret = "your-256-bit-secret"; auto signature_raw = /* compute HMAC SHA256 of signing_input with secret */; // 6. Encode signature auto signature_b64 = jwt::base::trim( jwt::base::encode(signature_raw) ); // 7. Construct final JWT std::string token = signing_input + "." + signature_b64; std::cout << "Token: " << token << "\n"; } ``` -------------------------------- ### Get Specific Payload Claim Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Retrieves a specific payload claim by its name (e.g., 'iss', 'sub', 'aud', custom names). Throws jwt::error::claim_not_present_exception if the claim does not exist. ```cpp basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const ``` -------------------------------- ### Verify JWT Token Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/verify-verifier.md Use jwt::verify() to create a verifier and then chain methods to configure verification rules. Finally, call verify() on the decoded token. ```cpp auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs256{\"secret\") .leeway(30) // seconds .with_issuer(\"auth.example.com\") .with_audience(\"urn:example:client\"); try { auto decoded_jwt = jwt::decode(token); verifier.verify(decoded_jwt); } catch (const std::exception& e) { // Handle error } ``` -------------------------------- ### Register Allowed Algorithm Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/verify-verifier.md Register a signing algorithm for verification. Verification succeeds if the token was signed with any of the allowed algorithms. ```cpp verifier.allow_algorithm(jwt::algorithm::hs256{\"secret\"); ``` -------------------------------- ### Manual JWT Decoding Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/base64-utilities.md Demonstrates manual JWT decoding by splitting the token into its three parts, decoding each part from Base64URL, and printing the header, payload, and signature length. This involves adding padding before decoding. ```cpp #include int main() { std::string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ".eyJzdWIiOiIxMjM0NTY3ODkwIn0..." ".TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"; // 1. Split by dots size_t first_dot = token.find('.'); size_t second_dot = token.find('.', first_dot + 1); std::string header_b64 = token.substr(0, first_dot); std::string payload_b64 = token.substr(first_dot + 1, second_dot - first_dot - 1); std::string signature_b64 = token.substr(second_dot + 1); // 2. Decode components (add padding first) auto header_json = jwt::base::decode( jwt::base::pad(header_b64) ); auto payload_json = jwt::base::decode( jwt::base::pad(payload_b64) ); auto signature_raw = jwt::base::decode( jwt::base::pad(signature_b64) ); std::cout << "Header: " << header_json << "\n"; std::cout << "Payload: " << payload_json << "\n"; std::cout << "Signature length: " << signature_raw.length() << " bytes\n"; } ``` -------------------------------- ### Get Header Claims as JSON Object Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Parses the decoded header JSON string and returns all header claims as a JSON object. This provides direct access to claims like 'alg', 'typ', etc. ```cpp typename json_traits::object_type get_header_json() const ``` -------------------------------- ### Work with Date Claims in JWT Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/basic-claim.md Demonstrates how to extract and format date-related claims like 'exp' (expiration time) and 'iat' (issued at) from a decoded JWT. ```cpp #include #include #include int main() { auto decoded = jwt::decode(token); // Extract expiration time auto exp_claim = decoded.get_payload_claim("exp"); auto exp_date = exp_claim.as_date(); // Convert to readable format auto exp_time_t = std::chrono::system_clock::to_time_t(exp_date); std::cout << "Expires: " << std::ctime(&exp_time_t); // Or use issued_at for convenience auto iat = decoded.get_issued_at(); auto iat_time_t = std::chrono::system_clock::to_time_t(iat); std::cout << "Issued at: " << std::ctime(&iat_time_t); } ``` -------------------------------- ### Get Payload Claims as JSON Object Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Parses the decoded payload JSON string and returns all payload claims as a JSON object. This provides direct access to claims like 'iss', 'sub', 'aud', etc. ```cpp typename json_traits::object_type get_payload_json() const ``` -------------------------------- ### Constructor with Default Decoder Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/decoded-jwt.md Parses a JWT token string using the built-in base64url decoder. Throws std::invalid_argument for invalid token format or std::runtime_error for decoding/parsing failures. ```cpp explicit decoded_jwt(const typename json_traits::string_type& token) ``` -------------------------------- ### Build with glaze Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/traits/CMakeLists.txt Configures a CMake executable to link jwt-cpp with glaze. Requires glaze to be found via find_package and C++23. ```cmake find_package(glaze CONFIG) if(TARGET glaze::glaze) add_executable(glaze-json glaze-json.cpp) target_compile_features(glaze-json PRIVATE cxx_std_23) target_link_libraries(glaze-json glaze::glaze jwt-cpp::jwt-cpp) endif() ``` -------------------------------- ### Usage of jwt::json::type Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/types.md Demonstrates how to use the `jwt::json::type` enumeration with a switch statement to handle different claim types retrieved from a decoded JWT. ```cpp auto claim = decoded.get_payload_claim("field"); switch (claim.get_type()) { case jwt::json::type::string: std::cout << claim.as_string() << "\n"; break; case jwt::json::type::integer: std::cout << claim.as_integer() << "\n"; break; default: std::cout << "Other type\n"; } ``` -------------------------------- ### Use Boost.JSON with JWT-CPP Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/configuration.md Integrates JWT-CPP with the Boost.JSON library. PicoJSON must be disabled, and the Boost.JSON traits header should be included. This enables JWT creation and decoding using Boost.JSON. ```cpp #define JWT_DISABLE_PICOJSON #include using traits = jwt::traits::boost_json; int main() { auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::hs256{"secret"}); } ``` -------------------------------- ### Build with Boost.JSON Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/traits/CMakeLists.txt Configures a CMake executable to link jwt-cpp with Boost.JSON. Requires Boost.JSON to be found via find_package. ```cmake find_package(Boost CONFIG COMPONENTS json) if(TARGET Boost::json) add_executable(boost-json boost-json.cpp) target_link_libraries(boost-json jwt-cpp::jwt-cpp Boost::json) endif() ``` -------------------------------- ### Project Directory Structure Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/MANIFEST.md Illustrates the organization of documentation files within the jwt-cpp project, categorizing them by their content such as README, types, errors, configuration, and API references. ```text output/ ├── README.md # Main index and navigation ├── types.md # Type definitions and enumerations ├── errors.md # Exception hierarchy and error handling ├── configuration.md # Build options and dependencies └── api-reference/ ├── decode-jwt.md # jwt::decode() ├── create-builder.md # jwt::create() ├── verify-verifier.md # jwt::verify() ├── decoded-jwt.md # decoded_jwt class ├── basic-claim.md # basic_claim class ├── algorithms.md # All signature algorithms ├── jwk-jwks.md # JSON Web Key parsing └── base64-utilities.md # Base64 functions ``` -------------------------------- ### Build with reflectcpp Source: https://github.com/thalhammer/jwt-cpp/blob/master/example/traits/CMakeLists.txt Configures a CMake executable to link jwt-cpp with reflectcpp. Requires reflectcpp to be found via find_package and C++20. ```cmake find_package(reflectcpp CONFIG) if(TARGET reflectcpp::reflectcpp) add_executable(reflectcpp-json reflectcpp-json.cpp) target_compile_features(reflectcpp-json PRIVATE cxx_std_20) target_link_libraries(reflectcpp-json jwt-cpp::jwt-cpp reflectcpp::reflectcpp) endif() ``` -------------------------------- ### Sign Token with Custom Base64URL Encoder Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/create-builder.md Illustrates signing a token using a custom base64url encoding function. The provided lambda trims padding and uses a specific alphabet. ```cpp auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::hs256{"secret"}, [](const std::string& data) { return jwt::base::trim( jwt::base::encode(data) ); }); ``` -------------------------------- ### Stream I/O for JWT Claims Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/basic-claim.md Demonstrates how to serialize a JWT claim to an output stream (like std::ostringstream) and deserialize a claim from an input stream (like std::istringstream). ```cpp #include #include int main() { // Write claim to stream auto claim = jwt::claim(std::string("test")); std::ostringstream oss; oss << claim; // Uses operator<< std::cout << "Claim JSON: " << oss.str() << "\n"; // Read claim from stream std::istringstream iss(R"({\"key\": \"value\"})"); jwt::claim parsed_claim; iss >> parsed_claim; // Uses operator>> std::cout << "Parsed type: " << (int)parsed_claim.get_type() << "\n"; } ``` -------------------------------- ### None Algorithm Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/algorithms.md The 'none' algorithm produces empty signatures. It is primarily for testing and should not be used in production. It has sign, verify, and name methods. ```APIDOC ## None Algorithm ### Description The "none" algorithm produces empty signatures. Primarily for testing; should not be used in production. ### Methods - `sign(const std::string& data, std::error_code& ec) const` - `verify(const std::string& data, const std::string& signature, std::error_code& ec) const` - `name() const` ### Parameters #### Sign Method Parameters - `data` (const std::string&): Data to sign (ignored). - `ec` (std::error_code&): Filled with error if signing fails. #### Verify Method Parameters - `data` (const std::string&): Data to verify against (ignored). - `signature` (const std::string&): Signature must be empty. - `ec` (std::error_code&): Filled with error if verification fails. ### Example ```cpp auto token = jwt::create() .set_type("JWT") .sign(jwt::algorithm::none{}); jwt::verify() .allow_algorithm(jwt::algorithm::none{}) .verify(decoded); ``` ``` -------------------------------- ### Create JWT Verifier Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/README.md Initializes a verifier for configuring and validating JWTs. Supports default clock and JSON traits. ```cpp template verifier verify(); ``` -------------------------------- ### Use Reflect-CPP with JWT-CPP Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/configuration.md Integrates JWT-CPP with the Reflect-CPP library. PicoJSON must be disabled, and the Reflect-CPP traits header should be included. This enables JWT creation and decoding using Reflect-CPP. ```cpp #define JWT_DISABLE_PICOJSON #include using traits = jwt::traits::reflect_json; int main() { auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::hs256{"secret"}); } ``` -------------------------------- ### Verifier - Algorithm Configuration Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/api-reference/verify-verifier.md Configure the allowed signing algorithms for token verification. The verifier will accept tokens signed by any of the registered algorithms. ```APIDOC ## allow_algorithm ### Description Registers a signing algorithm for verification. Verification succeeds if the token was signed with any of the allowed algorithms. ### Method Signature ```cpp template verifier& allow_algorithm(Algorithm alg) ``` ### Parameters #### Parameters - **alg** (Algorithm) - Required - Algorithm instance (e.g., `jwt::algorithm::hs256{"secret"}`). ### Returns `*this` for method chaining. ``` -------------------------------- ### Use JsonCpp with JWT-CPP Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/configuration.md Integrates JWT-CPP with the JsonCpp library. PicoJSON must be disabled, and the JsonCpp traits header should be included. This enables JWT creation and decoding using JsonCpp. ```cpp #define JWT_DISABLE_PICOJSON #include using traits = jwt::traits::jsoncpp; int main() { auto token = jwt::create() .set_issuer("myapp") .sign(jwt::algorithm::hs256{"secret"}); } ``` -------------------------------- ### Integrate JWT-CPP with CMake using FetchContent Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/configuration.md Add JWT-CPP as a dependency to your CMake project using the FetchContent module. This method downloads and builds the library as part of your project's build process. ```cmake include(FetchContent) FetchContent_Declare(jwt-cpp URL https://github.com/Thalhammer/jwt-cpp/archive/v0.10.2.tar.gz ) FetchContent_MakeAvailable(jwt-cpp) target_link_libraries(my_app PUBLIC jwt-cpp::jwt-cpp) ``` -------------------------------- ### Algorithms Source: https://github.com/thalhammer/jwt-cpp/blob/master/_autodocs/MANIFEST.md Details on supported signature algorithms for JWTs. ```APIDOC ## Algorithms ### Description The jwt-cpp library supports a wide range of signature algorithms for signing and verifying JWTs. ### Supported Algorithms - **None**: `none` - **HMAC**: `HS256`, `HS384`, `HS512` - **RSA**: `RS256`, `RS384`, `RS512` - **ECDSA**: `ES256`, `ES384`, `ES512`, `ES256K` - **EdDSA**: `Ed25519`, `Ed448` - **PSS**: `PS256`, `PS384`, `PS512` ### Usage Algorithms are typically specified when creating a `builder` or configuring a `verifier`. ```