JJWT Implementation module providing concrete implementations of JSON Web Token (JWT) creation, parsing, verification, and cryptographic operations for Java and Android applications.
—
The JWT Building functionality in JJWT Implementation is centered around the DefaultJwtBuilder class, which provides a fluent API for creating JWT (unsecured), JWS (signed), and JWE (encrypted) tokens. This comprehensive builder supports all standard JWT operations with type-safe configuration.
The main factory for creating all types of JWT tokens.
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Claims;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.Provider;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Map;
// Basic builder creation
JwtBuilder builder = Jwts.builder();
// Builder with provider configuration
JwtBuilder configuredBuilder = Jwts.builder()
.provider(myJcaProvider)
.random(mySecureRandom);// Header configuration
JwtBuilder headerBuilder = Jwts.builder()
.header()
.keyId("my-key-id")
.type("JWT")
.contentType("application/json")
.add("custom-header", "value")
.and();
// Claims configuration
JwtBuilder claimsBuilder = Jwts.builder()
.claims()
.subject("john.doe")
.issuer("my-service")
.audience().add("api-clients").and()
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 3600000))
.id(UUID.randomUUID().toString())
.add("role", "admin")
.add("permissions", Arrays.asList("read", "write", "delete"))
.and();
// Content setting (for content JWTs)
JwtBuilder contentBuilder = Jwts.builder()
.content("Plain text payload")
.header().contentType("text/plain").and();
// Binary content
byte[] binaryData = "Binary payload".getBytes(StandardCharsets.UTF_8);
JwtBuilder binaryBuilder = Jwts.builder()
.content(binaryData)
.header().contentType("application/octet-stream").and();
// Stream content (for large payloads)
InputStream largeStream = new FileInputStream("large-file.json");
JwtBuilder streamBuilder = Jwts.builder()
.content(largeStream)
.header().contentType("application/json").and();// Simple unsecured JWT with claims
String unsecuredJwt = Jwts.builder()
.subject("user123")
.issuer("my-app")
.issuedAt(new Date())
.compact();
// Unsecured JWT with content payload
String contentJwt = Jwts.builder()
.content("{\"message\": \"Hello World\"}")
.header()
.contentType("application/json")
.and()
.compact();
// Custom claims JWT
Map<String, Object> customClaims = new HashMap<>();
customClaims.put("userId", 12345);
customClaims.put("roles", Arrays.asList("user", "admin"));
customClaims.put("metadata", Map.of("department", "engineering"));
String customJwt = Jwts.builder()
.claims(customClaims)
.subject("john.doe")
.compact();import io.jsonwebtoken.security.SecureDigestAlgorithm;
// Generate HMAC key
SecretKey hmacKey = Jwts.SIG.HS256.key().build();
// Create signed JWT with HMAC
String hmacJws = Jwts.builder()
.subject("authenticated-user")
.signWith(hmacKey) // Algorithm auto-detected
.compact();
// Explicit algorithm specification
String explicitHmacJws = Jwts.builder()
.claims()
.subject("user")
.issuer("auth-service")
.and()
.signWith(hmacKey, Jwts.SIG.HS512)
.compact();
// Using different HMAC strengths
SecretKey hs384Key = Jwts.SIG.HS384.key().build();
SecretKey hs512Key = Jwts.SIG.HS512.key().build();
String hs384Jws = Jwts.builder()
.subject("user")
.signWith(hs384Key)
.compact();import java.security.KeyPair;
import java.security.PrivateKey;
// Generate RSA key pair
KeyPair rsaKeyPair = Jwts.SIG.RS256.keyPair().build();
PrivateKey rsaPrivateKey = rsaKeyPair.getPrivate();
// Create RSA-signed JWT
String rsaJws = Jwts.builder()
.subject("enterprise-user")
.issuer("corporate-sso")
.signWith(rsaPrivateKey)
.compact();
// Different RSA signature algorithms
KeyPair rs384Pair = Jwts.SIG.RS384.keyPair().build();
KeyPair rs512Pair = Jwts.SIG.RS512.keyPair().build();
String rs384Jws = Jwts.builder()
.subject("user")
.signWith(rs384Pair.getPrivate(), Jwts.SIG.RS384)
.compact();
// RSA-PSS signatures
KeyPair ps256Pair = Jwts.SIG.PS256.keyPair().build();
String psJws = Jwts.builder()
.subject("user")
.signWith(ps256Pair.getPrivate(), Jwts.SIG.PS256)
.compact();// Generate EC key pairs for different curves
KeyPair ecP256Pair = Jwts.SIG.ES256.keyPair().build();
KeyPair ecP384Pair = Jwts.SIG.ES384.keyPair().build();
KeyPair ecP521Pair = Jwts.SIG.ES512.keyPair().build();
// ES256 (P-256 curve)
String es256Jws = Jwts.builder()
.subject("mobile-user")
.signWith(ecP256Pair.getPrivate())
.compact();
// ES384 (P-384 curve)
String es384Jws = Jwts.builder()
.subject("api-client")
.signWith(ecP384Pair.getPrivate(), Jwts.SIG.ES384)
.compact();
// EdDSA signatures (Ed25519)
KeyPair ed25519Pair = Jwts.SIG.EdDSA.keyPair().build();
String eddsaJws = Jwts.builder()
.subject("iot-device")
.signWith(ed25519Pair.getPrivate())
.compact();import io.jsonwebtoken.security.AeadAlgorithm;
// Generate content encryption key
SecretKey cek = Jwts.ENC.A256GCM.key().build();
// Direct encryption (key used directly)
String directJwe = Jwts.builder()
.subject("confidential-user")
.claim("ssn", "123-45-6789")
.claim("salary", 150000)
.encryptWith(cek, Jwts.KEY.DIRECT, Jwts.ENC.A256GCM)
.compact();
// Different content encryption algorithms
SecretKey a128Key = Jwts.ENC.A128GCM.key().build();
SecretKey a192Key = Jwts.ENC.A192GCM.key().build();
String a128Jwe = Jwts.builder()
.subject("user")
.encryptWith(a128Key, Jwts.KEY.DIRECT, Jwts.ENC.A128GCM)
.compact();import io.jsonwebtoken.security.KeyAlgorithm;
// AES Key Wrap
SecretKey kekKey = Jwts.KEY.A256KW.key().build();
String aesKwJwe = Jwts.builder()
.subject("wrapped-content-user")
.claim("confidential", "sensitive data")
.encryptWith(kekKey, Jwts.KEY.A256KW, Jwts.ENC.A256GCM)
.compact();
// Different key wrap strengths
SecretKey a128kwKey = Jwts.KEY.A128KW.key().build();
SecretKey a192kwKey = Jwts.KEY.A192KW.key().build();
String a128kwJwe = Jwts.builder()
.subject("user")
.encryptWith(a128kwKey, Jwts.KEY.A128KW, Jwts.ENC.A128GCM)
.compact();// RSA key encryption
KeyPair rsaEncPair = Jwts.KEY.RSA1_5.keyPair().build();
String rsaJwe = Jwts.builder()
.subject("enterprise-confidential")
.claim("department", "R&D")
.claim("clearance", "SECRET")
.encryptWith(rsaEncPair.getPublic(), Jwts.KEY.RSA1_5, Jwts.ENC.A256GCM)
.compact();
// RSA-OAEP encryption
KeyPair rsaOaepPair = Jwts.KEY.RSA_OAEP.keyPair().build();
String rsaOaepJwe = Jwts.builder()
.subject("user")
.encryptWith(rsaOaepPair.getPublic(), Jwts.KEY.RSA_OAEP, Jwts.ENC.A256GCM)
.compact();
// RSA-OAEP-256
KeyPair rsaOaep256Pair = Jwts.KEY.RSA_OAEP_256.keyPair().build();
String rsaOaep256Jwe = Jwts.builder()
.subject("user")
.encryptWith(rsaOaep256Pair.getPublic(), Jwts.KEY.RSA_OAEP_256, Jwts.ENC.A256GCM)
.compact();// Elliptic Curve Diffie-Hellman Ephemeral Static
KeyPair ecdhPair = Jwts.KEY.ECDH_ES.keyPair().build();
String ecdhJwe = Jwts.builder()
.subject("mobile-secure-user")
.claim("deviceId", "mobile-123")
.encryptWith(ecdhPair.getPublic(), Jwts.KEY.ECDH_ES, Jwts.ENC.A256GCM)
.compact();
// ECDH-ES with key wrapping
KeyPair ecdh128Pair = Jwts.KEY.ECDH_ES_A128KW.keyPair().build();
String ecdhKwJwe = Jwts.builder()
.subject("user")
.encryptWith(ecdh128Pair.getPublic(), Jwts.KEY.ECDH_ES_A128KW, Jwts.ENC.A256GCM)
.compact();import io.jsonwebtoken.CompressionAlgorithm;
// DEFLATE compression (standard)
String compressedJwt = Jwts.builder()
.subject("user-with-large-claims")
.claim("permissions", Arrays.asList(/* many permissions */))
.claim("metadata", largeMetadataMap)
.compressWith(Jwts.ZIP.DEF)
.signWith(secretKey)
.compact();
// GZIP compression (non-standard but supported)
String gzipJwt = Jwts.builder()
.subject("user")
.claim("largeData", veryLargeString)
.compressWith(Jwts.ZIP.GZIP)
.signWith(secretKey)
.compact();
// Compression with encryption
String compressedJwe = Jwts.builder()
.subject("user")
.claim("bigPayload", massiveDataStructure)
.compressWith(Jwts.ZIP.DEF)
.encryptWith(kekKey, Jwts.KEY.A256KW, Jwts.ENC.A256GCM)
.compact();import java.security.Provider;
import java.security.SecureRandom;
// Custom JCA Provider
Provider customProvider = new BouncyCastleProvider();
SecureRandom customRandom = SecureRandom.getInstanceStrong();
String providerJwt = Jwts.builder()
.provider(customProvider)
.random(customRandom)
.subject("provider-specific-user")
.signWith(secretKey)
.compact();
// Provider-specific key generation
SecretKey providerKey = Jwts.SIG.HS256.key()
.provider(customProvider)
.random(customRandom)
.build();import io.jsonwebtoken.io.Serializer;
import io.jsonwebtoken.jackson.io.JacksonSerializer;
// Custom JSON serializer
Serializer<Map<String, ?>> jsonSerializer = new JacksonSerializer<>();
String customSerializedJwt = Jwts.builder()
.json(jsonSerializer)
.subject("user")
.claim("complexObject", customObjectWithSpecialSerialization)
.signWith(secretKey)
.compact();import io.jsonwebtoken.impl.DefaultJwtHeaderBuilder;
// Rich header configuration
String headerJwt = Jwts.builder()
.header()
.type("JWT")
.contentType("application/json")
.add("custom", "header-value")
.add("version", "1.0")
.and()
.subject("user")
.signWith(secretKey)
.compact();import io.jsonwebtoken.impl.DefaultJweHeaderBuilder;
// JWE-specific headers
String jweWithHeaders = Jwts.builder()
.subject("encrypted-user")
.encryptWith(kekKey, Jwts.KEY.A256KW, Jwts.ENC.A256GCM)
.compact();
// Note: JWE headers are automatically managed by the encryption processimport io.jsonwebtoken.impl.DefaultClaimsBuilder;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
// Comprehensive claims building
String richClaimsJwt = Jwts.builder()
.claims()
// Standard claims
.issuer("https://auth.example.com")
.subject("user@example.com")
.audience()
.add("https://api.example.com")
.add("https://mobile.example.com")
.and()
.expiration(Date.from(Instant.now().plus(1, ChronoUnit.HOURS)))
.notBefore(Date.from(Instant.now().minus(5, ChronoUnit.MINUTES)))
.issuedAt(new Date())
.id(UUID.randomUUID().toString())
// Custom claims
.add("role", "administrator")
.add("permissions", Set.of("read", "write", "delete"))
.add("profile", Map.of(
"name", "John Doe",
"email", "john@example.com",
"department", "Engineering"
))
.add("features", Arrays.asList("feature-a", "feature-b"))
.and()
.signWith(secretKey)
.compact();
// Bulk claims addition
Map<String, Object> bulkClaims = new HashMap<>();
bulkClaims.put("organizationId", "org-123");
bulkClaims.put("tenantId", "tenant-456");
bulkClaims.put("scope", "api:read api:write");
String bulkClaimsJwt = Jwts.builder()
.claims(bulkClaims)
.subject("service-account")
.signWith(secretKey)
.compact();// Create a base builder template
JwtBuilder baseBuilder = Jwts.builder()
.issuer("my-service")
.issuedAt(new Date())
.header()
.type("JWT")
.and();
// Reuse for multiple tokens (note: each compact() creates new instance)
String userToken = baseBuilder
.subject("user-123")
.signWith(userKey)
.compact();
String adminToken = Jwts.builder()
.issuer("my-service")
.issuedAt(new Date())
.header()
.type("JWT")
.and()
.subject("admin-456")
.claim("role", "admin")
.signWith(adminKey)
.compact();// Create factory methods for common patterns
public static String createUserToken(String userId, String role, SecretKey key) {
return Jwts.builder()
.subject(userId)
.issuer("user-service")
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 3600000))
.claim("role", role)
.signWith(key)
.compact();
}
public static String createServiceToken(String serviceId, List<String> scopes, SecretKey key) {
return Jwts.builder()
.subject(serviceId)
.issuer("service-registry")
.audience().add("api-gateway").and()
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 7200000)) // 2 hours
.claim("scopes", scopes)
.signWith(key)
.compact();
}
// Usage
String token1 = createUserToken("john.doe", "user", hmacKey);
String token2 = createServiceToken("payment-service", Arrays.asList("payments:read", "payments:write"), serviceKey);The JWT Building functionality provides a comprehensive, type-safe, and fluent API for creating any type of JWT token with full control over headers, claims, security algorithms, and advanced features like compression and custom serialization.
Install with Tessl CLI
npx tessl i tessl/maven-io-jsonwebtoken--jjwt-impl