### Install Savant Build Tool Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Instructions for downloading, extracting, and setting up the Savant build tool if it is not already installed. This includes creating a symbolic link and updating the PATH environment variable. ```bash mkdir ~/savant cd ~/savant wget http://savant.inversoft.org/org/savantbuild/savant-core/2.0.2/savant-2.0.2.tar.gz tar xvfz savant-2.0.2.tar.gz ln -s ./savant-2.0.2 current export PATH=$PATH:~/savant/current/bin/ ``` -------------------------------- ### JWT Domain Object Examples Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Demonstrates the usage of Algorithm, KeyType, Header, and KeyPair objects. These examples show how to instantiate and configure these objects for JWT operations. ```java import io.fusionauth.jwt.domain.Algorithm; import io.fusionauth.jwt.domain.Header; import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.domain.KeyPair; import io.fusionauth.jwt.domain.KeyType; // Algorithm examples Algorithm sigAlgorithm = Algorithm.RS256; String algorithmName = sigAlgorithm.getName(); // "SHA256withRSA" // KeyType example KeyType keyType = KeyType.RSA; String typeAlgorithm = keyType.getAlgorithm(); // "RSA" // Header example Header header = new Header(Algorithm.HS256) .set("kid", "key-001") .set("x5t", "thumbprint"); // KeyPair example (from generation) KeyPair keyPair = new KeyPair( "-----BEGIN PRIVATE KEY-----\n...", "-----BEGIN PUBLIC KEY-----\n..." ); ``` -------------------------------- ### Minimal JWT Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/README.md A basic example demonstrating JWT creation, encoding with HMAC, and decoding. Requires the HMAC secret. ```java JWT jwt = new JWT().setIssuer("issuer"); String token = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer("secret")); JWT decoded = JWT.getDecoder().decode(token, HMACVerifier.newVerifier("secret")); ``` -------------------------------- ### Complete JWK Operations Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-json-web-keys.md Demonstrates various JWK operations including retrieving keys from an issuer, building JWKs from PEM format, adding custom properties, and parsing JWKs from JSON. This example covers common use cases for JWK management. ```java import io.fusionauth.jwks.domain.JSONWebKey; import io.fusionauth.jwks.JSONWebKeySetHelper; import io.fusionauth.jwt.json.Mapper; import java.nio.charset.StandardCharsets; import java.security.PublicKey; import java.util.HashMap; import java.util.List; import java.util.Map; // Retrieve keys from a provider List keys = JSONWebKeySetHelper.retrieveKeysFromIssuer("https://accounts.google.com"); // Create a map for quick lookup by kid Map publicKeys = new HashMap<>(); for (JSONWebKey key : keys) { if (key.kid != null) { publicKeys.put(key.kid, JSONWebKey.parse(key)); } } // Build a JWK from a local key String pem = "-----BEGIN PUBLIC KEY-----\n..."; JSONWebKey localJwk = JSONWebKey.build(pem); String json = localJwk.toJSON(); // Add custom properties JSONWebKey enhanced = JSONWebKey.build(pem) .add("custom_id", "my-key-identifier") .add("environment", "production"); // Parse from JSON byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8); JSONWebKey parsed = Mapper.deserialize(jsonBytes, JSONWebKey.class); PublicKey reconstructed = JSONWebKey.parse(parsed); ``` -------------------------------- ### Minimal JWT Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/README.md A basic example demonstrating the creation, encoding, and decoding of a JWT using an HMAC signer. ```APIDOC ## Minimal JWT Example ### Description This example shows the fundamental steps of creating a JWT, signing it with an HMAC algorithm, and then decoding it. ### Method Direct Java API calls ### Usage ```java JWT jwt = new JWT().setIssuer("issuer"); String token = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer("secret")); JWT decoded = JWT.getDecoder().decode(token, HMACVerifier.newVerifier("secret")); ``` ``` -------------------------------- ### RSA Signing Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/README.md Demonstrates how to sign a JWT using an RSA private key. ```APIDOC ## RSA Signing Example ### Description This example illustrates signing a JWT using an RSA private key with the RS256 algorithm. ### Method Direct Java API calls ### Usage ```java RSASigner signer = RSASigner.newSHA256Signer(privateKeyPem); String token = JWT.getEncoder().encode(jwt, signer); ``` ``` -------------------------------- ### Complete JWT Example with OpenID Connect Claims Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-utilities.md A comprehensive example demonstrating the generation, signing, and verification of an ID token with OpenID Connect claims like `at_hash` and `nonce`. It includes key generation, JWK creation, and token encoding/decoding. ```java import io.fusionauth.jwt.JWTUtils; import io.fusionauth.jwt.OpenIDConnect; import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.domain.KeyPair; import io.fusionauth.jwt.domain.Algorithm; import io.fusionauth.jwks.domain.JSONWebKey; import io.fusionauth.jwt.rsa.RSASigner; import io.fusionauth.jwt.rsa.RSAVerifier; import java.time.ZoneOffset; import java.time.ZonedDateTime; // Generate keys KeyPair keyPair = JWTUtils.generate2048_RSAKeyPair(); String secret = JWTUtils.generateSHA256_HMACSecret(); // Build JWK with thumbprint JSONWebKey jwk = JSONWebKey.build(keyPair.publicKey); String kid = JWTUtils.generateJWS_kid_S256(jwk); // Create ID token with OpenID Connect claims String accessToken = "SlAV32hkKG..."; JWT idToken = new JWT() .setIssuer("https://auth.example.com") .setSubject("user123") .setAudience("client123") .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60)) .addClaim("at_hash", OpenIDConnect.at_hash(accessToken, Algorithm.RS256)) .addClaim("nonce", "n-0S6_WzA2Mj"); // Sign and encode RSASigner signer = RSASigner.newSHA256Signer(keyPair.privateKey, kid); String token = JWT.getEncoder().encode(idToken, signer); // Inspect header without verifying Header header = JWTUtils.decodeHeader(token); String keyId = header.getString("kid"); // Verify and decode RSAVerifier verifier = RSAVerifier.newVerifier(keyPair.publicKey); JWT verifiedToken = JWT.getDecoder().decode(token, verifier); String atHash = verifiedToken.getString("at_hash"); ``` -------------------------------- ### OIDC Integration Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/README.md Shows how to integrate with OpenID Connect by retrieving keys from a JWKS endpoint and decoding a token. ```APIDOC ## OIDC Integration Example ### Description This example demonstrates integrating with OpenID Connect by fetching public keys from a JWKS endpoint and using them to verify and decode a JWT. ### Method Direct Java API calls ### Usage ```java List keys = JSONWebKeySetHelper.retrieveKeysFromIssuer(issuer); // Convert to Map JWT decoded = JWT.getDecoder().decode(token, verifierMap); ``` ``` -------------------------------- ### Minimal JWT Create, Encode, and Decode Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md A complete minimal example demonstrating how to create, encode, and decode a JWT using HMAC-SHA256. Requires Java 17 and the fusionauth-jwt library. ```java import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.hmac.*; import java.time.ZoneOffset; import java.time.ZonedDateTime; // Create JWT jwt = new JWT() .setIssuer("issuer") .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(1)); // Encode String token = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer("secret")); // Decode JWT decoded = JWT.getDecoder().decode(token, HMACVerifier.newVerifier("secret")); // Use System.out.println(decoded.issuer); ``` -------------------------------- ### RSA Signing Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/README.md Demonstrates how to sign a JWT using an RSA private key. Ensure the private key is loaded correctly. ```java RSASigner signer = RSASigner.newSHA256Signer(privateKeyPem); String token = JWT.getEncoder().encode(jwt, signer); ``` -------------------------------- ### Build Project with Maven Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Install the project dependencies and build the artifact using Maven. This is a standard command for Maven projects. ```bash $ mvn install ``` -------------------------------- ### Complete PEM Key Workflow Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-pem-keys.md Demonstrates a full workflow including decoding private and public keys from a file, encoding them, saving to new files, and decoding from a PEM string. ```java import io.fusionauth.pem.PEMDecoder; import io.fusionauth.pem.PEMEncoder; import io.fusionauth.pem.domain.PEM; import java.nio.file.Files; import java.nio.file.Paths; import java.security.PrivateKey; import java.security.PublicKey; // Decode a private key from file PEMDecoder decoder = new PEMDecoder(); PEM pem = decoder.decode(Paths.get("private_key.pem")); PrivateKey privateKey = pem.getPrivateKey(); PublicKey publicKey = pem.getPublicKey(); // Encode the keys PEMEncoder encoder = new PEMEncoder(); String privateKeyPem = encoder.encode(privateKey); String publicKeyPem = encoder.encode(publicKey); // Save to files Files.write(Paths.get("exported_private.pem"), privateKeyPem.getBytes()); Files.write(Paths.get("exported_public.pem"), publicKeyPem.getBytes()); // Load from PEM string String pemString = "-----BEGIN PRIVATE KEY-----\n...-----END PRIVATE KEY-----"; PEM decoded = PEM.decode(pemString); PrivateKey key = decoded.getPrivateKey(); ``` -------------------------------- ### JWT Creation and Signing Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Demonstrates how to create a JWT with standard and custom claims, sign it using a specific algorithm and key, and then encode it. This is useful for generating JWTs for various authentication and authorization scenarios. ```java import io.fusionauth.jwt.JWT; import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.rsa.RSASigner; import java.time.ZoneOffset; import java.time.ZonedDateTime; // Create a JWT with an expiration date JWT jwt = new JWT() .setAudience("urn:example:aud") .setIssuer("urn:example:iss") .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC)) .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(1)) .addClaim("custom_claim", "custom_value"); // Sign the JWT using the RS256 algorithm and a private key String encodedJWT = JWT.encode(jwt, RSASigner.newRS256Signer(privateKey)); ``` -------------------------------- ### Example RSA Private Key JWK JSON Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md An example JSON representation of an RSA private key in JWK format, containing all components necessary for signing and decryption. ```json { "p": "9dy6wUxA0eOHopUP-E5QjDzuW8rXdaQMR566oDJ1qL0iD0koQAB9X3hboB-2Rru0aATu6WDW-jd4mgtYnXO8ow", "kty": "RSA", "q": "6Nfc6c8meTRkVRAHCF24LB5GLfsjoMB0tOeEO9w9Ous1a4o-D24bAePMUImAp3woFoNDRfWtlNktOqLel5Pjew", "d": "C0G3QGI6OQ6tvbCNYGCqq043YI_8MiBl7C5dqbGZmx1ewdJBhMNJPStuckhskURaDwk4-8VBW9SlvcfSJJrnZhgFMjOYSSsBtPGBIMIdM5eSKbenCCjO8Tg0BUh_xa3CHST1W4RQ5rFXadZ9AeNtaGcWj2acmXNO3DVETXAX3x0", "e": "AQAB", "use": "sig", "qi": "XLE5O360x-MhsdFXx8Vwz4304-MJg-oGSJXCK_ZWYOB_FGXFRTfebxCsSYi0YwJo-oNu96bvZCuMplzRI1liZw", "dp": "32QGgDmjr9GX3N6p2wh1YWa_gMHmUSqUScLseUA_7eijeNYU70pCoCtAvVXzDYPhoJ3S4lQuIL2kI_tpMe8GFw", "dq": "21tJjqeN-k-mWhCwX2xTbpTSzsyy4uWMzUTy6aXxtUkTWY2yK70yClS-Df2MS70G0za0MPtjnUAAgSYhB7HWcw", "n": "359ZykLITko_McOOKAtpJRVkjS5itwZxzjQidW2X6tBEOYCH4LZbwfj8fGGvlUtzpyuwnYuIlNX8TvZLTenOk45pphXr5PMCMKi7YZgkhd6_t_oeHnXY-4bnDLF1r9OUFKwj6C-mFFM-woKc-62tuK6QJiuc-5bFfn9wRL15K1E" } ``` -------------------------------- ### Complete JWT Workflow Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-encoder-decoder.md Illustrates a full JWT lifecycle: creating, encoding with HMAC, and decoding with verifier lookup by key ID (kid). Includes setting claims, expiration, and handling clock skew. ```java import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.JWTEncoder; import io.fusionauth.jwt.JWTDecoder; import io.fusionauth.jwt.hmac.HMACSigner; import io.fusionauth.jwt.hmac.HMACVerifier; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; // Create and encode a JWT JWT jwt = new JWT() .setIssuer("auth.example.com") .setSubject("user123") .setAudience("api.example.com") .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(1)) .addClaim("email", "user@example.com"); HMACSigner signer = HMACSigner.newSHA256Signer("secret-key", "key-001"); String token = JWT.getEncoder().encode(jwt, signer); // Decode with verifier lookup by kid Map verifiers = new HashMap<>(); verifiers.put("key-001", HMACVerifier.newVerifier("secret-key")); verifiers.put("key-002", HMACVerifier.newVerifier("other-secret")); JWT decodedJWT = JWT.getDecoder() .withClockSkew(30) // Allow 30 seconds of clock skew .decode(token, verifiers); System.out.println("Issuer: " + decodedJWT.issuer); System.out.println("Email: " + decodedJWT.getString("email")); ``` -------------------------------- ### Example JWK JSON with Custom Properties Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md An example JSON representation of an Elliptic Curve (EC) JWK that includes custom properties like 'boom' and 'more'. ```json { "alg" : "ES256", "boom" : "goes the dynamite", "crv" : "P-256", "kty" : "EC", "more" : "cowbell", "use" : "sig", "x" : "NIWpsIea0qzB22S0utDG8dGFYqEInv9C7ZgZuKtwjno", "y" : "iVFFtTgiInz_fjh-n1YqbibnUb2vtBZFs3wPpQw3mc0" } ``` -------------------------------- ### PEM Key Encoding and Decoding Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Shows how to encode private and public keys into PEM format and decode them back. This is useful for importing or exporting keys from/to PEM files, a common format for storing cryptographic keys. ```java import io.fusionauth.security.pem.PEMDecoder; import io.fusionauth.security.pem.PEMEncoder; import java.security.KeyPair; // Assume 'keyPair' is a java.security.KeyPair object // Encode the private key to PEM format String privatePEM = PEMEncoder.encode(keyPair.getPrivate()); // Encode the public key to PEM format String publicPEM = PEMEncoder.encode(keyPair.getPublic()); // Decode a private key from PEM format java.security.PrivateKey decodedPrivate = PEMDecoder.decodePrivateKey(privatePEM); // Decode a public key from PEM format java.security.PublicKey decodedPublic = PEMDecoder.decodePublicKey(publicPEM); ``` -------------------------------- ### Complete JWT Creation, Encoding, and Decoding Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md This snippet demonstrates the full lifecycle of a JWT: creating a token with various claims, encoding it using an HMAC-SHA256 signer with a secret key, and then decoding and verifying the token. It also shows how to access claims and check for expiration. ```java import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.JWTEncoder; import io.fusionauth.jwt.JWTDecoder; import io.fusionauth.jwt.hmac.HMACSigner; import io.fusionauth.jwt.hmac.HMACVerifier; import java.time.ZoneOffset; import java.time.ZonedDateTime; // Create a JWT JWT jwt = new JWT() .setIssuer("https://example.com") .setSubject("user123") .setAudience("api.example.com") .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC)) .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60)) .setUniqueId("jwt-id-001") .addClaim("email", "user@example.com") .addClaim("roles", Arrays.asList("admin", "user")); // Encode with HMAC-SHA256 HMACSigner signer = HMACSigner.newSHA256Signer("secret-key"); JWTEncoder encoder = JWT.getEncoder(); String encodedJWT = encoder.encode(jwt, signer); // Decode and verify HMACVerifier verifier = HMACVerifier.newVerifier("secret-key"); JWTDecoder decoder = JWT.getDecoder(); JWT decodedJWT = decoder.decode(encodedJWT, verifier); // Access claims String issuer = decodedJWT.issuer; String email = decodedJWT.getString("email"); List roles = decodedJWT.getList("roles"); // Check expiration if (decodedJWT.isExpired()) { System.out.println("Token is expired"); } ``` -------------------------------- ### JWT Decoding and Verification Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Shows how to decode and verify a JWT using a specific algorithm and public key. This is essential for validating incoming JWTs to ensure their authenticity and integrity. ```java import io.fusionauth.jwt.JWT; import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.rsa.RSAPublicKeyVerifier; // Decode and verify the JWT using the RS256 algorithm and a public key JWT decodedJWT = JWT.decode(encodedJWT, RSAPublicKeyVerifier.newRS256Verifier(publicKey)); // Access claims from the decoded JWT String customValue = decodedJWT.getClaim("custom_claim", String.class); boolean isExpired = decodedJWT.isExpired(); ``` -------------------------------- ### Example RSA Public Key JWK JSON Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md An example JSON representation of an RSA public key in JWK format, typically used for signature verification. ```json { "e": "AQAB", "kty": "RSA", "n": "Auchby3lZKHbiAZrTkJh79hJvgC3W7STSS4y6UZEhhxx3m3W2hD8qCyw6BEyrciPpwou-vmeDN7qBSk2QKqTTjlg5Pkf8O4z8d9HAlBTUDg4p98qLFOF2EFWWTiFbQwAP2qODOIv9WCAM2rkXEPwGiF962XAoOwiSmldeDu7Uo5A-bnTi0z3oNu4qm_48kv90o9CMiELszE9jsfoH32WE71HDqhsRjVNddDJ81e5zxBN8UEmaR-gmWqa63laON2KANPugJP7PrYJ_PC9ilQfV3F1rDpqbvlFQkshohJ39VrVpEtSRmJ12nqTFuspXLApekOyic3J9jo6ZI7o3IdQmy3bpnJIT_U", "use": "sig" } ``` -------------------------------- ### Create Empty Header Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Initializes a new, empty Header object. This is typically used as a starting point before setting specific header claims. ```java public Header() ``` -------------------------------- ### JSON Web Key (JWK) Generation Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Demonstrates how to generate RSA, EC, or EdDSA keys and represent them as JSON Web Keys (JWKs). This is useful for managing cryptographic keys in a standardized format, especially for OIDC integration. ```java import io.fusionauth.jwt.domain.KeyType; import io.fusionauth.jwt.domain.KeyPair; import io.fusionauth.jwt.rsa.RSAKeyGenerator; // Generate an RSA key pair KeyPair keyPair = RSAKeyGenerator.generate(KeyType.RS256, 2048); // Get the public JWK String publicKeyJWK = keyPair.getPublicKey().toJSON(); // Get the private JWK String privateKeyJWK = keyPair.getPrivateKey().toJSON(); ``` -------------------------------- ### Error Handling and Exceptions Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Detailed reference for exception classes, including when they are thrown, how to fix them, code examples, security implications, and best practices for error handling. ```APIDOC ## Error Handling and Exceptions ### Description This section provides a comprehensive guide to the exception hierarchy and error handling strategies within the FusionAuth JWT library. It aims to help developers understand, anticipate, and resolve errors effectively. ### Exception Reference: - **15+ exception classes**: Each exception is documented with: - **When thrown**: The specific conditions under which the exception occurs. - **How to fix**: Guidance on resolving the error. - **Code examples**: Illustrative code snippets demonstrating error scenarios and fixes. ### Security Implications: - Discussion on how errors might relate to security vulnerabilities and best practices to mitigate them. ### Best Practices: - **Clock skew and expiration handling**: Specific advice on managing time-related validation errors. - **Common error patterns**: Identification and solutions for frequently encountered issues. - **General error handling patterns**: Recommended approaches for robust error management in applications using the library. ``` -------------------------------- ### HMAC Signing and Verification Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Illustrates using HMAC algorithms (HS256, HS384, HS512) for signing and verifying JWTs. This method is suitable when the same secret key is shared between the issuer and the verifier. ```java import io.fusionauth.jwt.JWT; import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.hmac.HMACSigner; import io.fusionauth.jwt.hmac.HMACVerifier; // Secret key for HMAC signing byte[] secretKey = "your-secret-key".getBytes(); // Create and sign JWT with HS256 JWT jwt = new JWT().setSubject("user-id"); String encodedJWT = JWT.encode(jwt, HMACSigner.newHS256Signer(secretKey)); // Decode and verify JWT with HS256 JWT decodedJWT = JWT.decode(encodedJWT, HMACVerifier.newHS256Verifier(secretKey)); ``` -------------------------------- ### Get Claim as List Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a List of Objects. Use this for claims that are arrays or lists. ```java public List getList(String key) ``` -------------------------------- ### Get JWT Decoder Instance Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Obtain an instance of JWTDecoder to verify and decode JWTs. This is the entry point for JWT decoding operations. ```java JWTDecoder decoder = JWT.getDecoder(); JWT jwt = decoder.decode(encodedJWT, verifier); ``` -------------------------------- ### JWT Utility: Key Generation Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Provides examples of generating various types of cryptographic keys using JWTUtils, including RSA, EC, and EdDSA. This is useful for creating keys programmatically for signing and verification. ```java import io.fusionauth.jwt.domain.KeyType; import io.fusionauth.jwt.domain.KeyPair; import io.fusionauth.jwt.rsa.RSAKeyGenerator; import io.fusionauth.jwt.ec.ECKeyGenerator; import io.fusionauth.jwt.eddsa.EdDSAKeyGenerator; // Generate RSA key pair KeyPair rsaKeyPair = RSAKeyGenerator.generate(KeyType.RS256, 2048); // Generate EC key pair KeyPair ecKeyPair = ECKeyGenerator.generate(KeyType.ES256); // Generate EdDSA key pair KeyPair eddsaKeyPair = EdDSAKeyGenerator.generate(KeyType.Ed25519); ``` -------------------------------- ### Verify JWT with ECVerifier Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-signers.md Example of verifying a JWT using an ECVerifier created from a public key file. This ensures the token's signature is valid using EC cryptography. ```java ECVerifier verifier = ECVerifier.newVerifier(Paths.get("ec_public_key.pem")); JWT jwt = JWT.getDecoder().decode(token, verifier); ``` -------------------------------- ### Sign JWT with RSASigner Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-signers.md Example of signing a JWT using an RSASigner created from a PEM-encoded private key. Ensure the private key file exists and is correctly formatted. ```java String pem = new String(Files.readAllBytes(Paths.get("private_key.pem"))); RSASigner signer = RSASigner.newSHA256Signer(pem, "key-001"); String token = JWT.getEncoder().encode(jwt, signer); ``` -------------------------------- ### Enable Third-Party JCE Provider Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Insert a third-party JCE provider, such as Bouncy Castle FIPS, into the Java Security provider list. No code changes are required after this setup. ```java // Insert the provider ahead of the JCA. Security.insertProviderAt(new BouncyCastleFipsProvider(), 1); ``` -------------------------------- ### Get JWT Encoder Instance Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Obtain an instance of JWTEncoder to sign and encode JWTs. This is the entry point for JWT encoding operations. ```java JWTEncoder encoder = JWT.getEncoder(); String encodedJWT = encoder.encode(jwt, signer); ``` -------------------------------- ### Handle PEMDecoderException Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/errors.md Catch `PEMDecoderException` when decoding a PEM-encoded key file. This example illustrates handling errors related to file access or invalid PEM formatting. ```java try { PEM pem = new PEMDecoder().decode(Paths.get("key.pem")); } catch (PEMDecoderException e) { System.err.println("Failed to decode PEM: " + e.getMessage()); } ``` -------------------------------- ### Time Machine JWT Decoding Example Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-encoder-decoder.md Demonstrates how to use TimeMachineJWTDecoder to check token validity at specific past or future timestamps. Supports expiration and not-before checks relative to a provided 'now' timestamp and allows for clock skew. ```java ZonedDateTime testTime = ZonedDateTime.of(2019, 6, 1, 12, 0, 0, 0, ZoneOffset.UTC); JWTDecoder decoder = JWT.getTimeMachineDecoder(testTime); JWT jwt = decoder.decode(token, verifier); ZonedDateTime afterExpiration = ZonedDateTime.of(2019, 6, 2, 12, 0, 0, 0, ZoneOffset.UTC); deployer = JWT.getTimeMachineDecoder(afterExpiration); try { jwt = decoder.decode(token, verifier); } catch (JWTExpiredException e) { System.out.println("Token expired as expected"); } ``` -------------------------------- ### Get Header Claim Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a specific claim from the JWT header, such as 'kid' or 'typ'. Provide the header property name to get its value. ```java public Object getHeaderClaim(String name) ``` -------------------------------- ### Get Custom Claims Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves only the non-standard custom claims from the JWT. Use this to isolate user-defined claims. ```java public Map getOtherClaims() ``` -------------------------------- ### Get Claim as Boolean Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a Boolean. Use this for boolean claims. ```java public Boolean getBoolean(String key) ``` -------------------------------- ### Build Project with Savant Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Initialize the project build using the Savant build tool. This command is used for projects managed with Savant. ```bash $ sb int ``` -------------------------------- ### Get Claim as Integer Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value as an Integer. This method can access both registered and custom claims. ```APIDOC ## JWT.getInteger(String key) ### Description Returns a claim value as an Integer. This method can access both registered and custom claims. ### Method `public Integer getInteger(String key)` ### Parameters #### Path Parameters - **key** (String) - Required - The name of the claim to retrieve ### Returns The claim value as an Integer, or null if not found. ``` -------------------------------- ### Get Claim as String Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value as a String. This method can access both registered and custom claims. ```APIDOC ## JWT.getString(String key) ### Description Returns a claim value as a String. This method can access both registered and custom claims. ### Method `public String getString(String key)` ### Parameters #### Path Parameters - **key** (String) - Required - The name of the claim to retrieve ### Returns The claim value as a String, or null if not found. ``` -------------------------------- ### Get Header Property Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Retrieves the value of a specified header property. Returns null if the property is not found. ```java public Object get(String name) ``` -------------------------------- ### Get Algorithm Name Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Returns the JCA algorithm name for the Algorithm enum. This is useful for JCA operations. ```java public String getName() ``` -------------------------------- ### Get All JWT Claims Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md Retrieve all claims from a JWT, either as raw epoch seconds or with ZonedDateTime objects. ```java // All claims as map Map allClaims = jwt.getAllClaims(); // With ZonedDateTime objects Map rawClaims = jwt.getRawClaims(); // With epoch seconds ``` -------------------------------- ### Handling Missing Private Key Exception Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/errors.md Shows how to create an RSASigner and catch a MissingPrivateKeyException if the provided PEM string does not contain a private key. ```java String pem = "-----BEGIN PUBLIC KEY-----\n..."; // Public key try { RSASigner signer = RSASigner.newSHA256Signer(pem); } catch (MissingPrivateKeyException e) { System.err.println("PEM does not contain a private key"); } ``` -------------------------------- ### Get Claim as Double Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a Double. Use this for floating-point numeric claims. ```java public Double getDouble(String key) ``` -------------------------------- ### Create HMAC Signers with Different Hash Strengths Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Demonstrates how to create HMAC signers using SHA-384 and SHA-512 hash algorithms for stronger security. ```java Signer signer384 = HMACSigner.newSHA384Signer("too many secrets"); Signer signer512 = HMACSigner.newSHA512Signer("too many secrets"); ``` -------------------------------- ### Get Key Type Algorithm Name Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Returns the general algorithm name associated with a KeyType enum value. ```java public String getAlgorithm() ``` -------------------------------- ### JSON Web Key (JWK) Handling Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Documentation for the JSONWebKey class, factory methods, instance methods, and related utilities for managing JWKs, including PEM conversion and OIDC integration. ```APIDOC ## JSON Web Key (JWK) Handling ### Description This section covers the `JSONWebKey` class and associated utilities for working with JSON Web Keys (JWKs), which are used to represent cryptographic keys in a standard format. ### Key Components: - **JSONWebKey Class**: Properties and methods for JWK objects. - **Factory Methods**: Creating JWKs from PEM format, public keys, private keys, and certificates. - **Instance Methods**: `toJSON` for serialization, `add` for key manipulation. - **JSONWebKeyBuilder**: For constructing JWKs programmatically. - **JSONWebKeyParser**: For parsing JWK representations. - **JSONWebKeySetHelper**: Provides 5 methods specifically for OpenID Connect (OIDC) integration, such as fetching JWKS. - **JWKUtils**: Utilities for generating JWK thumbprints. ### Example: - **Complete example with OIDC integration**: Demonstrates how to use JWKs in the context of OpenID Connect. ``` -------------------------------- ### JSONWebKey Instance Methods Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-json-web-keys.md Methods for interacting with a JSONWebKey instance. ```APIDOC ## toJSON() ### Description Serializes the JSONWebKey to JSON string format. ### Method ```java public String toJSON() ``` ### Returns - **json** (`String`) - JSON representation of the JWK ### Example ```java JSONWebKey jwk = JSONWebKey.build(publicKey); String json = jwk.toJSON(); System.out.println(json); // Output: {"alg":"RS256","e":"AQAB","kty":"RSA","n":"...","use":"sig"} ``` ## add(String, Object) ### Description Adds a custom property to the JWK (added to the `other` map). ### Method ```java public JSONWebKey add(String name, Object value) ``` ### Parameters #### Path Parameters - **name** (`String`) - Required - Property name - **value** (`Object`) - Required - Property value ### Returns - **this** (`JSONWebKey`) ### Example ```java JSONWebKey jwk = JSONWebKey.build(publicKey) .add("custom_property", "custom_value") .add("another", 123); ``` ``` -------------------------------- ### Get Claim as Number Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value as a generic Number. This is useful when the exact numeric type is unknown or varies. ```java public Number getNumber(String key) ``` -------------------------------- ### Create KeyPair from PEM Strings Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Initializes a KeyPair object using PEM-encoded strings for both the private and public keys. The private key should be in PKCS#8 or PKCS#1 format, and the public key in X.509 format. ```java public KeyPair(String privateKey, String publicKey) ``` -------------------------------- ### Create Header with Algorithm Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Constructs a Header object specifying the signing algorithm. This is typically the first step in creating a JWT. ```java public Header(Algorithm algorithm) ``` -------------------------------- ### Get Claim as BigDecimal Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a BigDecimal. Use this for precise decimal arithmetic claims. ```java public BigDecimal getBigDecimal(String key) ``` -------------------------------- ### Types and Enums Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Reference for enums like Algorithm and KeyType, domain objects such as Header and KeyPair, and documented exception classes. ```APIDOC ## Types and Enums ### Description This section provides reference documentation for the various types, enums, and domain objects used within the FusionAuth JWT library, as well as its exception hierarchy. ### Enums: - **Algorithm**: Defines 14 supported cryptographic algorithms (e.g., HS256, RS256, ES256, Ed25519). - **KeyType**: Defines 4 key types (e.g., `RSA`, `EC`, `OCT`). ### Domain Objects: - **Header**: Represents the JWT header structure. - **KeyPair**: Represents a pair of public and private keys. ### Exception Hierarchy: - **15+ exception classes**: Detailed documentation for each exception, including when they are thrown and how to handle them. ### Buildable Interface: - Documentation for the `Buildable` interface, likely used for fluent object construction. ``` -------------------------------- ### Get Claim as BigInteger Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a BigInteger. Use this for arbitrarily large integer claims. ```java public BigInteger getBigInteger(String key) ``` -------------------------------- ### Get PSS Salt Length Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Returns the salt length in bytes for RSA-PSS algorithms. Throws an exception if the algorithm is not RSA-PSS. ```java public int getSaltLength() ``` -------------------------------- ### JSONWebKeyBuilder Methods Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-json-web-keys.md Methods for constructing JSONWebKey objects using a fluent builder pattern. ```APIDOC ## JSONWebKeyBuilder ### build(String) Builds a JSONWebKey from PEM. #### Parameters - **encodedPEM** (String) - Required - PEM-encoded key ``` -------------------------------- ### Get PSS Digest Algorithm Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/types.md Retrieves the message digest algorithm for RSA-PSS algorithms. Throws an exception if the algorithm is not RSA-PSS. ```java public String getDigest() ``` -------------------------------- ### Sign and Encode JWT with RSA (SHA-512) Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Shows how to create an RSA signer using a SHA-512 hash for JWT signing. The private key file is necessary. ```java // Build an RSA signer using a SHA5124 hash Signer signer = RSASigner.newSHA512Signer(new String(Files.readAllBytes(Paths.get("private_key.pem")))); ``` -------------------------------- ### Handle JSONWebKeyParserException Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/errors.md Catch `JSONWebKeyParserException` when parsing an invalid JWK string. This example demonstrates handling missing required fields in the JWK. ```java String invalidJwk = "{\"kty\":\"RSA\"}"; // Missing 'n' and 'e' try { JSONWebKey jwk = Mapper.deserialize(invalidJwk.getBytes(), JSONWebKey.class); PublicKey key = JSONWebKey.parse(jwk); } catch (JSONWebKeyParserException e) { System.err.println("Invalid JWK: " + e.getMessage()); } ``` -------------------------------- ### RSA Imports Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md Import classes for RSA signing and verification, including PSS variants. ```java import io.fusionauth.jwt.rsa.RSASigner; import io.fusionauth.jwt.rsa.RSAVerifier; import io.fusionauth.jwt.rsa.RSAPSSSigner; import io.fusionauth.jwt.rsa.RSAPSSVerifier; ``` -------------------------------- ### PEM Key Handling Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/MANIFEST.txt Documentation for PEM key decoding and encoding classes, key generation utilities, and related domain objects for managing keys in PEM format. ```APIDOC ## PEM Key Handling ### Description This section details the classes and utilities for handling keys in Privacy-Enhanced Mail (PEM) format, including decoding, encoding, and generation. ### PEM Decoding: - **PEMDecoder Class**: Includes 3 methods for decoding PEM-encoded keys and certificates. ### PEM Encoding: - **PEMEncoder Class**: Provides 4 methods for encoding keys into PEM format. ### Key Generation: - **KeyUtils**: Offers 8+ methods for generating various types of cryptographic keys (RSA, EC, EdDSA, HMAC). ### Domain Objects: - **PEM domain object**: Represents PEM-encoded data. - **KeyPair domain object**: Represents a pair of public and private keys. ### Exceptions: - **PEMDecoderException**, **PEMEncoderException**: Documented exceptions related to PEM processing. ### Example: - **Complete key generation and usage example**: Illustrates the process of generating keys, encoding them to PEM, and using them. ``` -------------------------------- ### Get Claim as Map Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a Map of String to Object. Use this for claims that are JSON objects. ```java public Map getMap(String key) ``` -------------------------------- ### OpenID Connect Import Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md Import the class for OpenID Connect specific JWT functionalities. ```java import io.fusionauth.jwt.OpenIDConnect; ``` -------------------------------- ### Get Claim as Long Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a Long. Use this when you expect a numeric claim that can be represented as a Long. ```java public Long getLong(String key) ``` -------------------------------- ### Generate RSA Key Pair, Sign and Verify JWT Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-pem-keys.md This snippet shows how to generate a 2048-bit RSA key pair, create a JWT, sign it using the private key, and then verify the signature using the public key. It covers the essential steps for JWT creation and validation. ```java import io.fusionauth.jwt.domain.KeyPair; import io.fusionauth.jwt.JWTUtils; import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.rsa.RSASigner; import io.fusionauth.jwt.rsa.RSAVerifier; import java.time.ZoneOffset; import java.time.ZonedDateTime; // Generate a new RSA key pair KeyPair keyPair = JWTUtils.generate2048_RSAKeyPair(); String privateKeyPem = keyPair.privateKey; String publicKeyPem = keyPair.publicKey; // Create and sign a JWT JWT jwt = new JWT() .setIssuer("auth.example.com") .setSubject("user123") .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(1)); RSASigner signer = RSASigner.newSHA256Signer(privateKeyPem); String token = JWT.getEncoder().encode(jwt, signer); // Verify with public key RSAVerifier verifier = RSAVerifier.newVerifier(publicKeyPem); JWT decodedJWT = JWT.getDecoder().decode(token, verifier); System.out.println("Token verified: " + decodedJWT.issuer); ``` -------------------------------- ### JSONWebKey build methods Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-json-web-keys.md Builds a JSONWebKey from a PublicKey, PrivateKey, or Certificate. ```APIDOC ## JSONWebKey build(PublicKey) ### Description Builds a JSONWebKey from a PublicKey. ### Method ```java public JSONWebKey build(PublicKey publicKey) ``` ## JSONWebKey build(PrivateKey) ### Description Builds a JSONWebKey from a PrivateKey. ### Method ```java public JSONWebKey build(PrivateKey privateKey) ``` ## JSONWebKey build(Certificate) ### Description Builds a JSONWebKey from a Certificate. ### Method ```java public JSONWebKey build(Certificate certificate) ``` ``` -------------------------------- ### Sign and Encode JWT with RSA (SHA-384) Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Demonstrates building an RSA signer with a SHA-384 hash for signing JWTs. Requires the private key file. ```java // Build an RSA signer using a SHA-384 hash Signer signer = RSASigner.newSHA384Signer(new String(Files.readAllBytes(Paths.get("private_key.pem")))); ``` -------------------------------- ### Sign JWT with ECSigner Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-signers.md Example of signing a JWT using an ECSigner created from a PEM-encoded private key. This uses the P-256 curve and SHA-256. ```java String pem = new String(Files.readAllBytes(Paths.get("ec_private_key.pem"))); ECSigner signer = ECSigner.newSHA256Signer(pem); String token = JWT.getEncoder().encode(jwt, signer); ``` -------------------------------- ### Get Claim as Object Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value as a generic Object. Use this as a fallback when the claim type is unknown or needs dynamic handling. ```java public Object getObject(String key) ``` -------------------------------- ### Sign and Encode JWT with EC (SHA-512) Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Shows how to create an EC signer using a SHA-512 hash for JWT signing. The private key file is necessary. ```java // Build an EC signer using a SHA-512 hash Signer signer = ECSigner.newSHA512Signer(new String(Files.readAllBytes(Paths.get("private_key.pem")))); ``` -------------------------------- ### Handling Missing Verifier Exception Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/errors.md Demonstrates how to provide multiple verifiers when decoding a JWT and catching a MissingVerifierException if no verifier matches the JWT's algorithm. ```java try { JWT jwt = JWT.getDecoder().decode(token, new HMACVerifier.newVerifier("secret"), // supports HS256, HS384, HS512 new RSAVerifier.newVerifier(publicKey) // supports RS256, RS384, RS512 ); } catch (MissingVerifierException e) { System.err.println("No verifier found for this JWT's algorithm"); } ``` -------------------------------- ### Get Claim as Float Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves a claim value and attempts to cast it to a Float. Use this for floating-point numeric claims where Float precision is sufficient. ```java public Float getFloat(String key) ``` -------------------------------- ### Create ECVerifier from public key file path or PublicKey object Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-signers.md Provides additional factory methods for creating EC verifiers from a file path to a public key or directly from a Java PublicKey object. ```java newVerifier(Path), newVerifier(PublicKey) ``` -------------------------------- ### Get All Claims as Java Types Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-jwt.md Retrieves all claims from the JWT, converting temporal claims to ZonedDateTime objects. This provides claims with their appropriate Java types. ```java public Map getAllClaims() ``` -------------------------------- ### Sign and Encode JWT with EC (SHA-384) Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/README.md Demonstrates building an EC signer with a SHA-384 hash for JWT signing. The private key file is required. ```java // Build an EC signer using a SHA-384 hash Signer signer = ECSigner.newSHA384Signer(new String(Files.readAllBytes(Paths.get("private_key.pem")))); ``` -------------------------------- ### Verify JWT with RSAVerifier Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/api-reference-signers.md Example of verifying a JWT using an RSAVerifier created from a public key file. The verifier ensures the token's signature is valid. ```java RSAVerifier verifier = RSAVerifier.newVerifier(Paths.get("public_key.pem")); JWT jwt = JWT.getDecoder().decode(token, verifier); ``` -------------------------------- ### HMAC Imports Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md Import classes for HMAC signing and verification. ```java import io.fusionauth.jwt.hmac.HMACSigner; import io.fusionauth.jwt.hmac.HMACVerifier; ``` -------------------------------- ### Handle JSONWebKeySetException Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/errors.md Catch `JSONWebKeySetException` when retrieving keys from a JWKS endpoint. This example shows handling potential network or JSON parsing issues during JWKS retrieval. ```java try { List keys = JSONWebKeySetHelper.retrieveKeysFromJWKS( "https://example.com/jwks" ); } catch (JSONWebKeySetException e) { System.err.println("Failed to retrieve JWKS: " + e.getMessage()); // Fallback to cached keys or retry } ``` -------------------------------- ### Create and Sign a JWT with HMAC Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md Create a JWT with standard claims and sign it using an HMAC SHA256 signer. Ensure you have the HMACSigner class imported. ```java import io.fusionauth.jwt.domain.JWT; import io.fusionauth.jwt.hmac.HMACSigner; import java.time.ZoneOffset; import java.time.ZonedDateTime; // Create JWT with standard claims JWT jwt = new JWT() .setIssuer("https://auth.example.com") .setSubject("user123") .setAudience("api.example.com") .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(1)) .addClaim("email", "user@example.com"); // Sign with HMAC HMACSigner signer = HMACSigner.newSHA256Signer("shared-secret"); String token = JWT.getEncoder().encode(jwt, signer); ``` -------------------------------- ### EC Imports Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/quick-reference.md Import classes for Elliptic Curve (EC) signing and verification. ```java import io.fusionauth.jwt.ec.ECSigner; import io.fusionauth.jwt.ec.ECVerifier; ``` -------------------------------- ### Add FusionAuth JWT Maven Dependency Source: https://github.com/fusionauth/fusionauth-jwt/blob/main/_autodocs/INDEX.md Include the FusionAuth JWT library as a dependency in your Maven project. This example shows the XML configuration for Maven Central. ```xml io.fusionauth fusionauth-jwt 6.0.0 ```