### Complete JWT Verification Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt-verifier.md A comprehensive example showing how to create a JWT, set up a JWTVerifier with specific algorithms and claims, and then verify the token. It includes error handling for verification failures. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.*; public class VerificationExample { public static void main(String[] args) { String secret = "your-secret-key"; Algorithm algorithm = Algorithm.HMAC256(secret); // Create a token String token = JWT.create() .withIssuer("auth0") .withSubject("user@example.com") .withClaim("role", "admin") .withExpiresAt(new Date(System.currentTimeMillis() + 3600000)) .sign(algorithm); // Create verifier JWTVerifier verifier = JWT.require(algorithm) .withIssuer("auth0") .withSubject("user@example.com") .withClaim("role", "admin") .acceptLeeway(10) .build(); // Verify token try { DecodedJWT decodedJWT = verifier.verify(token); System.out.println("Token verified!"); System.out.println("Issuer: " + decodedJWT.getIssuer()); System.out.println("Subject: " + decodedJWT.getSubject()); } catch (JWTVerificationException e) { System.err.println("Token verification failed!"); } } } ``` -------------------------------- ### Implementation Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Provides a concrete implementation of the ECDSAKeyProvider interface named SimpleECDSAKeyProvider. This example shows how to provide public and private keys for ECDSA operations. ```APIDOC ### Implementation Example ```java import com.auth0.jwt.interfaces.ECDSAKeyProvider; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; public class SimpleECDSAKeyProvider implements ECDSAKeyProvider { private final ECPublicKey publicKey; private final ECPrivateKey privateKey; public SimpleECDSAKeyProvider(ECPublicKey publicKey, ECPrivateKey privateKey) { this.publicKey = publicKey; this.privateKey = privateKey; } @Override public ECPublicKey getPublicKeyById(String keyId) { return publicKey; } @Override public ECPrivateKey getPrivateKey() { return privateKey; } @Override public String getPrivateKeyId() { return null; } } ``` ``` -------------------------------- ### Complete JWT Decode and Access Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md A comprehensive example demonstrating JWT creation, decoding, verification, and accessing various types of claims (header, standard payload, custom payload). ```java import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.*; public class DecodedJWTExample { public static void main(String[] args) { // Create a token Algorithm algorithm = Algorithm.HMAC256("secret"); String token = JWT.create() .withIssuer("myapp") .withSubject("user@example.com") .withAudience("api-1", "api-2") .withClaim("role", "admin") .withClaim("permissions", Arrays.asList("read", "write")) .withExpiresAt(new Date(System.currentTimeMillis() + 3600000)) .sign(algorithm); // Decode and verify DecodedJWT decoded = JWT.decode(token); // Access header claims System.out.println("Algorithm: " + decoded.getAlgorithm()); System.out.println("Type: " + decoded.getType()); // Access standard payload claims System.out.println("Issuer: " + decoded.getIssuer()); System.out.println("Subject: " + decoded.getSubject()); System.out.println("Audience: " + decoded.getAudience()); System.out.println("Expires At: " + decoded.getExpiresAt()); // Access custom claims String role = decoded.getClaim("role").asString(); System.out.println("Role: " + role); List permissions = decoded.getClaim("permissions") .asList(String.class); System.out.println("Permissions: " + permissions); // Get all claims Map allClaims = decoded.getClaims(); System.out.println("Total claims: " + allClaims.size()); } } ``` -------------------------------- ### Usage with Algorithm Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Example of how to use an RSAKeyProvider with the Algorithm class to create an RSA256 algorithm instance. ```java Algorithm algorithm = Algorithm.RSA256(rsaKeyProvider); ``` -------------------------------- ### Example of JWTCreationException Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/errors.md Demonstrates how to catch a JWTCreationException that occurs when attempting to sign a JWT with a null algorithm. ```java try { String token = JWT.create() .withIssuer("auth0") .sign(null); // Null algorithm throws IllegalArgumentException -> JWTCreationException } catch (JWTCreationException e) { System.err.println("Failed to create token: " + e.getMessage()); } ``` -------------------------------- ### Create a JWT Builder Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt.md Use this static method to get a builder for constructing and signing JWT tokens. It's the starting point for token creation. ```java public static JWTCreator.Builder create() ``` ```java Algorithm algorithm = Algorithm.HMAC256("secret-key"); String token = JWT.create() .withIssuer("auth0") .withSubject("user123") .withClaim("role", "admin") .sign(algorithm); ``` -------------------------------- ### Usage Example for Algorithm Name Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Demonstrates how to create an HMAC256 algorithm and then retrieve its standard name using the getName() method. ```java Algorithm algorithm = Algorithm.HMAC256("secret"); System.out.println(algorithm.getName()); // Outputs: HS256 ``` -------------------------------- ### ECDSAKeyProvider Usage Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/types.md Demonstrates how to implement the ECDSAKeyProvider interface for signing and verification using ECDSA keys. In a real application, keys would be fetched from a secure source. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.ECDSAKeyProvider; import java.security.interfaces.*; public class ECDSAKeyProviderExample implements ECDSAKeyProvider { private ECPublicKey publicKey; private ECPrivateKey privateKey; private String privateKeyId; @Override public ECPublicKey getPublicKeyById(String keyId) { return publicKey; } @Override public ECPrivateKey getPrivateKey() { return privateKey; } @Override public String getPrivateKeyId() { return privateKeyId; } public static void main(String[] args) { ECDSAKeyProvider provider = new ECDSAKeyProviderExample(); Algorithm algorithm = Algorithm.ECDSA256(provider); } } ``` -------------------------------- ### RSAKeyProvider Usage Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/types.md Demonstrates how to implement the RSAKeyProvider interface for signing and verification using RSA keys. In a real application, keys would be fetched from a secure source. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.RSAKeyProvider; import java.security.interfaces.*; public class RSAKeyProviderExample implements RSAKeyProvider { private RSAPublicKey publicKey; private RSAPrivateKey privateKey; private String privateKeyId; @Override public RSAPublicKey getPublicKeyById(String keyId) { // In a real scenario, fetch from JWKS endpoint or keystore return publicKey; } @Override public RSAPrivateKey getPrivateKey() { return privateKey; } @Override public String getPrivateKeyId() { return privateKeyId; } public static void main(String[] args) { RSAKeyProvider provider = new RSAKeyProviderExample(); Algorithm algorithm = Algorithm.RSA256(provider); } } ``` -------------------------------- ### RSA256 Token Creation in Java Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Illustrates how to create a JWT signed with the RSA256 algorithm. This example generates a new RSA key pair for signing. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import java.security.KeyPairGenerator; import java.security.KeyPair; import java.util.Date; public class RSAExample { public static void main(String[] args) throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.generateKeyPair(); Algorithm algorithm = Algorithm.RSA256( (java.security.interfaces.RSAPublicKey) keyPair.getPublic(), (java.security.interfaces.RSAPrivateKey) keyPair.getPrivate() ); // Create token String token = JWT.create() .withIssuer("myapp") .withSubject("user123") .withExpiresAt(new Date(System.currentTimeMillis() + 3600000)) .sign(algorithm); System.out.println("Token: " + token); } } ``` -------------------------------- ### Creating RSA Algorithm with Key Provider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Shows how to create an RSA256 Algorithm instance using a SingleKeyRSAProvider. This provider is initialized with a public and private RSA key. The example also includes token creation and verification. ```java RSAKeyProvider provider = new SingleKeyRSAProvider(publicKey, privateKey); Algorithm algorithm = Algorithm.RSA256(provider); // Create token String token = JWT.create() .withIssuer("auth0") .sign(algorithm); // Verify token JWTVerifier verifier = JWT.require(algorithm) .withIssuer("auth0") .build(); verifier.verify(token); ``` -------------------------------- ### Usage Example: Verifying a Decoded JWT Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt-verifier.md Demonstrates the process of first decoding a JWT and then verifying it using a pre-configured verifier. This is useful when you need to inspect the token before full verification. ```java // First decode without verification DecodedJWT decoded = JWT.decode(token); // Later, verify it try { DecodedJWT verified = verifier.verify(decoded); } catch (JWTVerificationException e) { System.err.println("Verification failed: " + e.getMessage()); } ``` -------------------------------- ### Complete JWT Decoding and Claim Access Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-claim.md Demonstrates decoding a JWT and accessing various standard and custom claims. Shows how to retrieve claims as strings, arrays, maps, booleans, and doubles, and how to check for missing or null claims. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.*; public class ClaimExample { public static void main(String[] args) { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCIsInN1YiI6InVzZXIxMjMiLCJyb2xlIjoiYWRtaW4iLCJzY29wZXMiOlsicmVhZCIsIndyaXRlIl0sIm1ldGFkYXRhIjp7Im9yZyI6ImFjbWUiLCJkZXB0IjoiZW5naW5lZXJpbmcifSwiaXNfYWN0aXZlIjp0cnVlLCJjcmVkaXRzIjo5OTkuOTksImlhdCI6MTYwOTQ1OTIwMCwiZXhwIjoxNjA5NTQ1NjAwfQ.signature"; DecodedJWT decoded = JWT.decode(token); // Standard registered claims System.out.println("Issuer: " + decoded.getIssuer()); System.out.println("Subject: " + decoded.getSubject()); System.out.println("Issued At: " + decoded.getIssuedAt()); System.out.println("Expires At: " + decoded.getExpiresAt()); // String claim Claim roleClaim = decoded.getClaim("role"); String role = roleClaim.asString(); System.out.println("Role: " + role); // Array claim Claim scopesClaim = decoded.getClaim("scopes"); List scopes = scopesClaim.asList(String.class); System.out.println("Scopes: " + scopes); // Object claim Claim metadataClaim = decoded.getClaim("metadata"); Map metadata = metadataClaim.asMap(); System.out.println("Organization: " + metadata.get("org")); System.out.println("Department: " + metadata.get("dept")); // Boolean claim Boolean isActive = decoded.getClaim("is_active").asBoolean(); System.out.println("Is Active: " + isActive); // Double claim Double credits = decoded.getClaim("credits").asDouble(); System.out.println("Credits: " + credits); // Check for missing or null claims Claim optionalClaim = decoded.getClaim("optional_field"); if (optionalClaim.isMissing()) { System.out.println("Optional field is not present"); } Claim nullClaim = decoded.getClaim("nullable_field"); if (nullClaim.isNull()) { System.out.println("Nullable field is explicitly null"); } // Get all claims Map allClaims = decoded.getClaims(); System.out.println("Total claims: " + allClaims.size()); } } ``` -------------------------------- ### Get JWT Algorithm Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the 'alg' claim from the JWT header. This indicates the signing algorithm used. ```java String getAlgorithm() DecodedJWT decoded = JWT.decode(token); String algorithm = decoded.getAlgorithm(); // e.g., "HS256" ``` -------------------------------- ### Decode JWT and Access Claims Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Decode a JWT and access individual claims. This example shows how to retrieve string claims, array claims, and check if a claim is missing. ```java DecodedJWT decoded = JWT.decode(token); // Get a string claim Claim roleClaim = decoded.getClaim("role"); String role = roleClaim.asString(); // Get an array claim Claim scopesClaim = decoded.getClaim("scopes"); List scopes = scopesClaim.asList(String.class); // Check if claim exists Claim customClaim = decoded.getClaim("custom"); if (customClaim.isMissing()) { System.out.println("Claim not present"); } ``` -------------------------------- ### Java RSA Key Rotation Example Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md This snippet demonstrates a complete key rotation mechanism for RSA-signed JWTs. It includes a custom `RotatingKeyProvider` that manages multiple public keys and the current private key, enabling seamless token verification and signing with rotating credentials. Ensure you have the `java-jwt` library added to your project dependencies. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.RSAKeyProvider; import com.auth0.jwt.interfaces.DecodedJWT; import java.security.KeyPairGenerator; import java.security.KeyPair; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.util.HashMap; import java.util.Map; public class KeyRotationExample { static class RotatingKeyProvider implements RSAKeyProvider { private final Map publicKeys; private final RSAPrivateKey currentPrivateKey; private final String currentKeyId; public RotatingKeyProvider( Map publicKeys, RSAPrivateKey currentPrivateKey, String currentKeyId) { this.publicKeys = publicKeys; this.currentPrivateKey = currentPrivateKey; this.currentKeyId = currentKeyId; } @Override public RSAPublicKey getPublicKeyById(String keyId) { RSAPublicKey key = publicKeys.get(keyId); if (key == null) { throw new RuntimeException("Key not found: " + keyId); } return key; } @Override public RSAPrivateKey getPrivateKey() { return currentPrivateKey; } @Override public String getPrivateKeyId() { return currentKeyId; } } public static void main(String[] args) throws Exception { // Generate old and new keys KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair oldKeyPair = generator.generateKeyPair(); KeyPair newKeyPair = generator.generateKeyPair(); // Set up key provider Map publicKeys = new HashMap<>(); publicKeys.put("2024-key-1", (RSAPublicKey) oldKeyPair.getPublic()); publicKeys.put("2024-key-2", (RSAPublicKey) newKeyPair.getPublic()); RSAKeyProvider provider = new RotatingKeyProvider( publicKeys, (RSAPrivateKey) newKeyPair.getPrivate(), "2024-key-2" ); Algorithm algorithm = Algorithm.RSA256(provider); // Create token with new key String token = JWT.create() .withIssuer("myapp") .withSubject("user@example.com") .sign(algorithm); System.out.println("Token created with new key"); // Verify token - automatically uses correct key based on kid JWTVerifier verifier = JWT.require(algorithm) .withIssuer("myapp") .build(); DecodedJWT decoded = verifier.verify(token); System.out.println("Token verified successfully"); System.out.println("Key ID used: " + decoded.getKeyId()); } } ``` -------------------------------- ### Get Not Before Instant Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Not Before ("nbf") claim from the JWT payload as an Instant object. Returns null if the claim is not present. ```java default Instant getNotBeforeAsInstant() ``` ```java DecodedJWT decoded = JWT.decode(token); Instant notBefore = decoded.getNotBeforeAsInstant(); ``` -------------------------------- ### Get Claim as Instant Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-claim.md Retrieves a JWT claim value as a Java Instant object. This is a modern alternative to `asDate()` and is useful for timestamp claims. ```java default Instant asInstant() ``` ```java DecodedJWT decoded = JWT.decode(token); Instant createdAt = decoded.getClaim("iat").asInstant(); ``` -------------------------------- ### JWT.create() Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt.md Creates a new JWT builder for constructing and signing JWT tokens. This method is the starting point for creating new tokens, allowing you to set claims and sign them with a specified algorithm. ```APIDOC ## JWT.create() ### Description Creates a new JWT builder for constructing and signing JWT tokens. ### Method `public static JWTCreator.Builder create()` ### Parameters None ### Returns `JWTCreator.Builder` - A builder instance for configuring JWT claims and signing the token. ### Usage Example ```java Algorithm algorithm = Algorithm.HMAC256("secret-key"); String token = JWT.create() .withIssuer("auth0") .withSubject("user123") .withClaim("role", "admin") .sign(algorithm); ``` ``` -------------------------------- ### Get JWT Type Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the 'typ' claim from the JWT header, which typically identifies the token type as 'JWT'. ```java String getType() DecodedJWT decoded = JWT.decode(token); String type = decoded.getType(); // Typically "JWT" ``` -------------------------------- ### Usage with ECDSA Algorithms Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Demonstrates how to create Algorithm instances for ECDSA256, ECDSA384, and ECDSA512 using an ECDSAKeyProvider. This is typically done when initializing the signing/verification algorithm. ```java Algorithm algorithm = Algorithm.ECDSA256(ecdsaKeyProvider); Algorithm algorithm = Algorithm.ECDSA384(ecdsaKeyProvider); Algorithm algorithm = Algorithm.ECDSA512(ecdsaKeyProvider); ``` -------------------------------- ### Get JWT Claims as Instant Source: https://github.com/auth0/java-jwt/blob/master/MIGRATION_GUIDE.md Retrieve the expiration, not-before, or issued-at claims from a decoded JWT as java.time.Instant objects. ```java Instant getExpiresAtAsInstant() ``` ```java Instant getNotBeforeAsInstant() ``` ```java Instant getIssuedAtAsInstant() ``` -------------------------------- ### Get Algorithm Name Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Retrieves the standard JWT name for the algorithm, such as 'HS256' or 'RS256'. This is useful for identifying the algorithm used. ```java public String getName() ``` -------------------------------- ### Decode JWT and Get Base64 Encoded Header Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieve the Base64-encoded header of the JWT. This is the first part of the token string. ```java DecodedJWT decoded = JWT.decode(token); String header = decoded.getHeader(); ``` -------------------------------- ### Create JWT with Registered Claims Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/types.md Demonstrates how to create a JWT and include standard registered claims using the `RegisteredClaims` constants. Ensure the `com.auth0.jwt` package and necessary algorithms are imported. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.RegisteredClaims; import com.auth0.jwt.algorithms.Algorithm; import java.util.Date; public class RegisteredClaimsExample { public static void main(String[] args) { Algorithm algorithm = Algorithm.HMAC256("secret"); // Creating a token with registered claims String token = JWT.create() .withClaim(RegisteredClaims.ISSUER, "myapp") .withClaim(RegisteredClaims.SUBJECT, "user@example.com") .withClaim(RegisteredClaims.AUDIENCE, "api-audience") .withClaim(RegisteredClaims.EXPIRES_AT, new Date(System.currentTimeMillis() + 3600000)) .withClaim(RegisteredClaims.ISSUED_AT, new Date()) .withClaim(RegisteredClaims.NOT_BEFORE, new Date()) .withClaim(RegisteredClaims.JWT_ID, "unique-token-id-123") .sign(algorithm); System.out.println("Token created with registered claims"); } } ``` -------------------------------- ### Get Private Key for Signing Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Retrieves the private key used for signing JWTs. This key is used for all signature generation operations. ```java R getPrivateKey() ``` -------------------------------- ### Usage with Algorithm Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Demonstrates how to use an ECDSAKeyProvider instance with different ECDSA algorithms (ECDSA256, ECDSA384, ECDSA512) when creating an Algorithm object. ```APIDOC ### Usage with Algorithm ```java Algorithm algorithm = Algorithm.ECDSA256(ecdsaKeyProvider); Algorithm algorithm = Algorithm.ECDSA384(ecdsaKeyProvider); Algorithm algorithm = Algorithm.ECDSA512(ecdsaKeyProvider); ``` ``` -------------------------------- ### Get Issuer Claim Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Issuer ("iss") claim from the JWT payload. Returns null if the claim is not present. ```java String getIssuer() ``` ```java DecodedJWT decoded = JWT.decode(token); String issuer = decoded.getIssuer(); // e.g., "https://example.auth0.com/" ``` -------------------------------- ### Create RSA384 Algorithm with RSAKeyProvider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Create an RSA384 algorithm instance by providing an RSAKeyProvider. This is useful for managing RSA keys. ```java public static Algorithm RSA384(RSAKeyProvider keyProvider) throws IllegalArgumentException ``` -------------------------------- ### Create and Sign a JWT with RS256 Source: https://github.com/auth0/java-jwt/blob/master/README.md Demonstrates how to create a JWT using the RS256 algorithm and configure claims. Ensure you handle JWTCreationException for invalid configurations. ```java try { Algorithm algorithm = Algorithm.RSA256(rsaPublicKey, rsaPrivateKey); String token = JWT.create() .withIssuer("auth0") .sign(algorithm); } catch (JWTCreationException exception){ // Invalid Signing configuration / Couldn't convert Claims. } ``` -------------------------------- ### Decode JWT and Get Base64 Encoded Signature Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieve the Base64-encoded signature of the JWT. This is the third part of the token string and is used for verification. ```java DecodedJWT decoded = JWT.decode(token); String signature = decoded.getSignature(); ``` -------------------------------- ### Decode JWT and Get Base64 Encoded Payload Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieve the Base64-encoded payload of the JWT. This is the second part of the token string and contains the claims. ```java DecodedJWT decoded = JWT.decode(token); String payload = decoded.getPayload(); ``` -------------------------------- ### RSA384(RSAKeyProvider keyProvider) Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Creates an RSA384 algorithm instance using a key provider, which supplies the necessary RSA keys. ```APIDOC ## Static Method: RSA384(RSAKeyProvider keyProvider) ### Description Creates an RSA384 algorithm using a key provider. ### Method Signature ```java public static Algorithm RSA384(RSAKeyProvider keyProvider) throws IllegalArgumentException ``` ### Parameters #### Parameters - **keyProvider** (RSAKeyProvider) - Required - Provider for public/private RSA keys ### Returns - **Algorithm** - An RSA384 algorithm instance ### Throws - **IllegalArgumentException** - If keyProvider is null ``` -------------------------------- ### Decode JWT and Get Original Token String Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Obtain the original JWT token string after decoding. This is useful for verification or logging purposes. ```java DecodedJWT decoded = JWT.decode(token); String originalToken = decoded.getToken(); ``` -------------------------------- ### Simple ECDSAKeyProvider Implementation Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md A basic implementation of the ECDSAKeyProvider interface. It holds a public and private EC key and returns them when requested. The private key ID is returned as null. ```java import com.auth0.jwt.interfaces.ECDSAKeyProvider; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; public class SimpleECDSAKeyProvider implements ECDSAKeyProvider { private final ECPublicKey publicKey; private final ECPrivateKey privateKey; public SimpleECDSAKeyProvider(ECPublicKey publicKey, ECPrivateKey privateKey) { this.publicKey = publicKey; this.privateKey = privateKey; } @Override public ECPublicKey getPublicKeyById(String keyId) { return publicKey; } @Override public ECPrivateKey getPrivateKey() { return privateKey; } @Override public String getPrivateKeyId() { return null; } } ``` -------------------------------- ### Using HeaderParams Constants to Create a JWT Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/types.md Demonstrates how to use HeaderParams constants like KEY_ID when creating a JWT with custom headers. Ensure the Algorithm and JWT classes are imported. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.HeaderParams; import com.auth0.jwt.algorithms.Algorithm; import java.util.HashMap; import java.util.Map; public class HeaderParamsExample { public static void main(String[] args) { Algorithm algorithm = Algorithm.HMAC256("secret"); Map headers = new HashMap<>(); headers.put(HeaderParams.KEY_ID, "2024-key-1"); String token = JWT.create() .withHeader(headers) .withIssuer("myapp") .sign(algorithm); } } ``` -------------------------------- ### Claim - Instant Conversion and Null Check Source: https://github.com/auth0/java-jwt/blob/master/MIGRATION_GUIDE.md Methods for converting a Claim to an Instant and checking if a claim is missing. ```APIDOC ## Claim - Instant Conversion and Null Check ### Description These methods on the `Claim` object allow you to get its value as a `java.time.Instant` and to check if the claim is present in the JWT. ### Method `Claim` ### Endpoints N/A (These are methods on a Claim object) ### Parameters None ### Response #### Success Response - `asInstant()`: Returns the claim's value as a `java.time.Instant`. Throws an exception if the claim is not an Instant or is null. - `isMissing()`: Returns `true` if the claim is not present in the JWT, `false` otherwise. ``` -------------------------------- ### Get Issued At Instant Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Issued At ("iat") claim from the JWT payload as an Instant object. Returns null if the claim is not present. ```java default Instant getIssuedAtAsInstant() ``` ```java DecodedJWT decoded = JWT.decode(token); Instant issuedAt = decoded.getIssuedAtAsInstant(); ``` -------------------------------- ### RSA Key Rotation with RotatingRSAKeyProvider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Demonstrates key rotation using RotatingRSAKeyProvider. This provider manages multiple public keys identified by IDs and a current private key. The token header will include the 'kid' of the signing key. ```java Map publicKeys = new HashMap<>(); publicKeys.put("2024-key-1", oldPublicKey); publicKeys.put("2024-key-2", currentPublicKey); RSAKeyProvider provider = new RotatingRSAKeyProvider( publicKeys, currentPrivateKey, "2024-key-2" ); Algorithm algorithm = Algorithm.RSA256(provider); // Token will have "kid": "2024-key-2" in header String token = JWT.create() .withIssuer("auth0") .sign(algorithm); // Verifier automatically selects correct key based on token's kid JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT decoded = verifier.verify(token); ``` -------------------------------- ### Get Issued At Date Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Issued At ("iat") claim from the JWT payload as a Date object. Returns null if the claim is not present. ```java Date getIssuedAt() ``` ```java DecodedJWT decoded = JWT.decode(token); Date issuedAt = decoded.getIssuedAt(); ``` -------------------------------- ### Get JWT Content Type Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the 'cty' claim from the JWT header. This is used when the payload is not a JSON object and is rarely used in standard JWTs. ```java String getContentType() DecodedJWT decoded = JWT.decode(token); String contentType = decoded.getContentType(); ``` -------------------------------- ### Retrieve Claim as Boolean Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-claim.md Use asBoolean() to get the claim's value as a Boolean. Returns null if the claim's value is not a boolean or cannot be converted to one. ```java DecodedJWT decoded = JWT.decode(token); Boolean isAdmin = decoded.getClaim("is_admin").asBoolean(); if (isAdmin != null && isAdmin) { System.out.println("User is admin"); } ``` -------------------------------- ### Create RSA256 Algorithm with KeyProvider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Use this method to create an RSA256 algorithm when you have a dynamic key provider. The key provider allows for dynamic key selection based on the key ID, which is useful for key rotation and multi-tenant scenarios. Ensure the keyProvider is not null. ```java public static Algorithm RSA256(RSAKeyProvider keyProvider) throws IllegalArgumentException ``` ```java RSAKeyProvider keyProvider = new RSAKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) { // Fetch public key from JWKS endpoint return publicKey; } @Override public RSAPrivateKey getPrivateKey() { return privateKey; } @Override public String getPrivateKeyId() { return "2024-rsa-key"; } }; Algorithm algorithm = Algorithm.RSA256(keyProvider); ``` -------------------------------- ### Get JWT Key ID Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the 'kid' claim from the JWT header, used to identify the specific key used for signing. Essential for key rotation. ```java String getKeyId() DecodedJWT decoded = JWT.decode(token); String keyId = decoded.getKeyId(); if (keyId != null) { // Fetch the correct key for verification } ``` -------------------------------- ### getAlgorithm() Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the algorithm used to sign the JWT from the header. ```APIDOC ## getAlgorithm() ### Description Returns the Algorithm ("alg") claim from the header. ### Method ```java String getAlgorithm() ``` ### Returns - **String**: The algorithm name (e.g., "HS256", "RS256") or null if not present ### Usage Example ```java DecodedJWT decoded = JWT.decode(token); String algorithm = decoded.getAlgorithm(); // e.g., "HS256" ``` ``` -------------------------------- ### Create RSA512 Algorithm with RSAKeyProvider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Use this method to create an RSA512 algorithm when you have an RSAKeyProvider that supplies the necessary RSA keys. Throws IllegalArgumentException if the keyProvider is null. ```java public static Algorithm RSA512(RSAKeyProvider keyProvider) throws IllegalArgumentException ``` -------------------------------- ### JWT Signing and Verification with RSAKeyProvider Source: https://github.com/auth0/java-jwt/blob/master/EXAMPLES.md Implement a custom RSAKeyProvider to dynamically fetch public and private keys for signing and verification, integrating with external key sources like JWKS. ```java JwkProvider provider = new JwkProviderBuilder("https://samples.auth0.com/") .cached(10, 24, TimeUnit.HOURS) .rateLimited(10, 1, TimeUnit.MINUTES) .build(); final RSAPrivateKey privateKey = // private key final String privateKeyId = // private key ID RSAKeyProvider keyProvider = new RSAKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String kid) { return (RSAPublicKey) jwkProvider.get(kid).getPublicKey(); } @Override public RSAPrivateKey getPrivateKey() { // return the private key used return rsaPrivateKey; } @Override public String getPrivateKeyId() { return rsaPrivateKeyId; } }; Algorithm algorithm = Algorithm.RSA256(keyProvider); //Use the Algorithm to create and verify JWTs. ``` -------------------------------- ### Create ECDSA384 Algorithm with ECKey Objects Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Instantiates an ECDSA384 algorithm using separate public and private ECKey objects. ```java public static Algorithm ECDSA384(ECPublicKey publicKey, ECPrivateKey privateKey) throws IllegalArgumentException ``` -------------------------------- ### Get Signing Key ID Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Retrieves the Key ID ('kid') used for signing, if it was provided by a KeyProvider. This is primarily used in key rotation scenarios and is null if not available. ```java public String getSigningKeyId() ``` -------------------------------- ### RSA512(RSAKeyProvider keyProvider) Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Creates an RSA512 algorithm using a key provider. This is useful for managing keys dynamically. ```APIDOC ## Static Method: RSA512(RSAKeyProvider keyProvider) ### Description Creates an RSA512 algorithm using a key provider. ### Method Signature ```java public static Algorithm RSA512(RSAKeyProvider keyProvider) throws IllegalArgumentException ``` ### Parameters * **keyProvider** (RSAKeyProvider) - Required - Provider for public/private RSA keys. ### Returns * `Algorithm` - An RSA512 algorithm instance. ### Throws * `IllegalArgumentException` - If keyProvider is null. ``` -------------------------------- ### Get Claim as Array Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-claim.md Retrieves a JWT claim value as an array of a specified type. Use this for claims that are arrays, such as 'scopes' or 'user_ids'. Throws JWTDecodeException if elements cannot be converted. ```java T[] asArray(Class clazz) throws JWTDecodeException ``` ```java DecodedJWT decoded = JWT.decode(token); // String array String[] scopes = decoded.getClaim("scopes").asArray(String.class); for (String scope : scopes) { System.out.println("Scope: " + scope); } // Integer array Integer[] ids = decoded.getClaim("user_ids").asArray(Integer.class); ``` -------------------------------- ### JWTCreator.Builder - Adding Instant Claims Source: https://github.com/auth0/java-jwt/blob/master/MIGRATION_GUIDE.md Methods for adding standard and custom claims with Instant values to a JWT. ```APIDOC ## JWTCreator.Builder - Adding Instant Claims ### Description These methods allow you to add standard JWT claims like `exp`, `nbf`, and `iat`, as well as custom claims, using `java.time.Instant` objects. ### Method `JWTCreator.Builder` ### Endpoints N/A (These are builder methods) ### Parameters #### `withExpiresAt(Instant expiresAt)` - **expiresAt** (Instant) - Required - The expiration time for the JWT. #### `withNotBefore(Instant notBefore)` - **notBefore** (Instant) - Required - The time before which the JWT must not be accepted. #### `withIssuedAt(Instant issuedAt)` - **issuedAt** (Instant) - Required - The time at which the JWT was issued. #### `withClaim(String claimName, Instant value)` - **claimName** (String) - Required - The name of the custom claim. - **value** (Instant) - Required - The Instant value for the custom claim. #### `withNullClaim(String claimName)` - **claimName** (String) - Required - The name of the claim to be set to null. ``` -------------------------------- ### Get JWT ID Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the JWT ID ("jti") claim from the payload, which provides a unique identifier for the token. Returns null if the claim is not present. ```java String getId() ``` ```java DecodedJWT decoded = JWT.decode(token); String jwtId = decoded.getId(); ``` -------------------------------- ### Claim Handling with Instant and Null Source: https://github.com/auth0/java-jwt/blob/master/MIGRATION_GUIDE.md Access claim values as java.time.Instant or check if a claim is missing. Supports retrieving claims with literal null values. ```java Instant asInstant() ``` ```java boolean isMissing() ``` -------------------------------- ### Get Not Before Date Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Not Before ("nbf") claim from the JWT payload as a Date object. The token is not considered valid before this time. Returns null if the claim is not present. ```java Date getNotBefore() ``` ```java DecodedJWT decoded = JWT.decode(token); Date notBefore = decoded.getNotBefore(); ``` -------------------------------- ### Get Subject Claim Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Subject ("sub") claim from the JWT payload, typically representing the user ID. Returns null if the claim is not present. ```java String getSubject() ``` ```java DecodedJWT decoded = JWT.decode(token); String subject = decoded.getSubject(); // e.g., "user@example.com" ``` -------------------------------- ### Create a JWT Verifier Builder Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt.md Initiates a JWT verifier builder with a specified algorithm for signature verification. Configure further claim checks before building the verifier. ```java public static Verification require(Algorithm algorithm) throws IllegalArgumentException ``` ```java Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey); JWTVerifier verifier = JWT.require(algorithm) .withIssuer("auth0") .withSubject("user123") .build(); DecodedJWT verified = verifier.verify(token); ``` -------------------------------- ### Verification - Adding Instant Claim Expectations Source: https://github.com/auth0/java-jwt/blob/master/MIGRATION_GUIDE.md Methods for setting expectations on JWT claims, including specific Instant values or custom validation logic. ```APIDOC ## Verification - Adding Instant Claim Expectations ### Description These methods allow you to configure the `Verification` object to expect specific values for claims, including exact `java.time.Instant` matches, or to define custom validation logic using a `BiPredicate`. ### Method `Verification` ### Endpoints N/A (These are configuration methods for verification) ### Parameters #### `withClaim(String name, Instant value)` - **name** (String) - Required - The name of the claim to verify. - **value** (Instant) - Required - The expected `java.time.Instant` value for the claim. #### `withClaim(String name, BiPredicate predicate)` - **name** (String) - Required - The name of the claim to verify. - **predicate** (BiPredicate) - Required - A predicate function that takes the `Claim` and `DecodedJWT` and returns `true` if the claim is valid, `false` otherwise. #### `withNullClaim(String name)` - **name** (String) - Required - The name of the claim that is expected to be null. ``` -------------------------------- ### HMAC256 Token Creation and Verification in Java Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Demonstrates how to create and verify a JWT signed with the HMAC256 algorithm. Ensure you have the Auth0 Java JWT library included in your project. ```java import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import java.util.Date; public class HMACExample { public static void main(String[] args) { Algorithm algorithm = Algorithm.HMAC256("your-secret-key"); // Create token String token = JWT.create() .withIssuer("myapp") .withSubject("user123") .withExpiresAt(new Date(System.currentTimeMillis() + 3600000)) .sign(algorithm); System.out.println("Token: " + token); // Verify token JWTVerifier verifier = JWT.require(algorithm) .withIssuer("myapp") .build(); verifier.verify(token); System.out.println("Token verified!"); } } ``` -------------------------------- ### Retrieve Claim as Integer Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-claim.md Use `asInt()` to get a claim value as an Integer. It attempts to convert numeric values and truncates decimals if necessary. Returns null if conversion fails. ```java Integer asInt() ``` ```java DecodedJWT decoded = JWT.decode(token); Integer userId = decoded.getClaim("user_id").asInt(); ``` -------------------------------- ### Get Expiration Time as Instant Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Expiration Time ("exp") claim from the JWT payload and returns it as an Instant object. Returns null if the claim is not present. ```java default Instant getExpiresAtAsInstant() ``` ```java DecodedJWT decoded = JWT.decode(token); Instant expiresAt = decoded.getExpiresAtAsInstant(); ``` -------------------------------- ### Builder.sign(Algorithm algorithm) Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt-creator.md Creates a complete JWT token by signing it with the specified algorithm. This is the final step in the JWT creation process. ```APIDOC ## Builder.sign(Algorithm algorithm) ### Description Creates a complete JWT token by signing with the provided algorithm. ### Method ```java public String sign(Algorithm algorithm) throws IllegalArgumentException, JWTCreationException ``` ### Parameters #### Path Parameters - **algorithm** (Algorithm) - Required - The algorithm to use for signing ### Returns - **String** - A complete JWT token with header, payload, and signature ### Throws - `IllegalArgumentException` - If algorithm is null - `JWTCreationException` - If claims could not be converted to valid JSON or there is a problem with the signing key ### Notes - The header "alg" claim is automatically set to the algorithm name - The header "typ" claim is set to "JWT" if not already provided - The "kid" claim is added to the header if the algorithm has a signing key ID ### Usage Example ```java Algorithm algorithm = Algorithm.HMAC256("secret-key"); String token = JWT.create() .withIssuer("auth0") .withSubject("user@example.com") .withExpiresAt(new Date(System.currentTimeMillis() + 3600000)) .sign(algorithm); ``` ``` -------------------------------- ### Create RSA384 Algorithm with RSAKey Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Use this method to create an RSA384 algorithm when you have an RSAKey object that encapsulates both public and private keys. ```java public static Algorithm RSA384(RSAKey key) throws IllegalArgumentException ``` -------------------------------- ### Get Expiration Time as Date Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves the Expiration Time ("exp") claim from the JWT payload and converts it to a Java Date object. Returns null if the claim is not present. ```java Date getExpiresAt() ``` ```java DecodedJWT decoded = JWT.decode(token); Date expiresAt = decoded.getExpiresAt(); if (expiresAt != null) { System.out.println("Token expires at: " + expiresAt); } ``` -------------------------------- ### Create ECDSA256 Algorithm with ECKey Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Instantiates an ECDSA256 algorithm using an ECKey object. Ensure the ECKey is properly configured. ```java public static Algorithm ECDSA256(ECKey key) throws IllegalArgumentException ``` -------------------------------- ### Get Public Key by ID Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Retrieves the public key used for verifying a JWT's signature. This method is called during verification, using the 'kid' from the JWT header to identify the correct key. ```java U getPublicKeyById(String keyId) ``` -------------------------------- ### Get Custom JWT Header Claim Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-decoded-jwt.md Retrieves a custom header claim by its name. Returns a Claim object, which will be a 'null claim' if the claim doesn't exist. Use isMissing() to check for existence. ```java Claim getHeaderClaim(String name) DecodedJWT decoded = JWT.decode(token); Claim customHeader = decoded.getHeaderClaim("custom-header"); if (!customHeader.isMissing()) { String value = customHeader.asString(); } ``` -------------------------------- ### Verify JWT Claim with Instant Value Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-jwt-verifier.md Use this method to verify that a specific JWT claim matches a given Instant. The claim value is compared against the provided instant. ```java Instant expectedInstant = Instant.parse("2021-01-01T00:00:00Z"); JWTVerifier verifier = JWT.require(algorithm) .withClaim("created_at", expectedInstant) .build(); ``` -------------------------------- ### JWKS Endpoint Integration with JWKSRSAKeyProvider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Illustrates using JWKSRSAKeyProvider to integrate with JWKS endpoints, commonly used in OAuth 2.0/OpenID Connect. The provider fetches public keys from a given URL, and the verifier automatically selects the correct key based on the token's 'kid'. ```java JWKSRSAKeyProvider provider = new JWKSRSAKeyProvider( "https://example.auth0.com/.well-known/jwks.json", null, // Don't sign tokens null ); Algorithm algorithm = Algorithm.RSA256(provider); // Always uses the correct key from JWKS endpoint JWTVerifier verifier = JWT.require(algorithm) .withIssuer("https://example.auth0.com/") .build(); // The provider fetches the appropriate public key based on token's kid DecodedJWT decoded = verifier.verify(thirdPartyToken); ``` -------------------------------- ### RSA256 with RSAKeyProvider Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/api-reference-algorithms.md Creates an RSA256 algorithm instance using an RSAKeyProvider, which allows for dynamic key selection based on the key ID. ```APIDOC ## Static Method: RSA256(RSAKeyProvider keyProvider) ### Description Creates an RSA256 algorithm using a key provider. ### Method Signature ```java public static Algorithm RSA256(RSAKeyProvider keyProvider) throws IllegalArgumentException ``` ### Parameters #### Parameters - **keyProvider** (RSAKeyProvider) - Required - Provider for public/private RSA keys ### Returns - **Algorithm** - An RSA256 algorithm instance ### Throws - **IllegalArgumentException** - If keyProvider is null ### Notes - The key provider allows dynamic key selection based on key ID ("kid"). - Useful for key rotation and multi-tenant scenarios. ### Usage Example ```java RSAKeyProvider keyProvider = new RSAKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) { // Fetch public key from JWKS endpoint return publicKey; } @Override public RSAPrivateKey getPrivateKey() { return privateKey; } @Override public String getPrivateKeyId() { return "2024-rsa-key"; } }; Algorithm algorithm = Algorithm.RSA256(keyProvider); ``` ``` -------------------------------- ### Get Private Key ID Source: https://github.com/auth0/java-jwt/blob/master/_autodocs/key-providers.md Returns the key ID associated with the private key. This ID is included in the JWT header's 'kid' claim, enabling recipients to select the correct public key for verification. ```java String getPrivateKeyId() ```