or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdio-utilities.mdjwt-operations.mdsecurity-jwk.mdtypes.md

jwt-operations.mddocs/

0

# JWT Operations

1

2

This document covers the core JWT building, parsing, and validation functionality of JJWT API.

3

4

## JWT Factory - Jwts

5

6

The `Jwts` class serves as the main entry point for JWT operations, providing factory methods and standard algorithm constants.

7

8

```java { .api }

9

public final class Jwts {

10

// Factory Methods

11

public static JwtBuilder builder();

12

public static JwtParserBuilder parser();

13

public static ClaimsBuilder claims();

14

public static HeaderBuilder header();

15

16

// Standard Algorithm Constants

17

public static final class SIG {

18

public static final MacAlgorithm HS256;

19

public static final MacAlgorithm HS384;

20

public static final MacAlgorithm HS512;

21

public static final SignatureAlgorithm RS256;

22

public static final SignatureAlgorithm RS384;

23

public static final SignatureAlgorithm RS512;

24

public static final SignatureAlgorithm PS256;

25

public static final SignatureAlgorithm PS384;

26

public static final SignatureAlgorithm PS512;

27

public static final SignatureAlgorithm ES256;

28

public static final SignatureAlgorithm ES384;

29

public static final SignatureAlgorithm ES512;

30

public static final SignatureAlgorithm EdDSA;

31

}

32

33

public static final class ENC {

34

public static final AeadAlgorithm A128GCM;

35

public static final AeadAlgorithm A192GCM;

36

public static final AeadAlgorithm A256GCM;

37

public static final AeadAlgorithm A128CBC_HS256;

38

public static final AeadAlgorithm A192CBC_HS384;

39

public static final AeadAlgorithm A256CBC_HS512;

40

}

41

42

public static final class KEY {

43

public static final KeyAlgorithm<SecretKey, SecretKey> DIRECT;

44

public static final KeyAlgorithm<SecretKey, SecretKey> A128KW;

45

public static final KeyAlgorithm<SecretKey, SecretKey> A192KW;

46

public static final KeyAlgorithm<SecretKey, SecretKey> A256KW;

47

public static final KeyAlgorithm<PublicKey, PrivateKey> RSA1_5;

48

public static final KeyAlgorithm<PublicKey, PrivateKey> RSA_OAEP;

49

public static final KeyAlgorithm<PublicKey, PrivateKey> RSA_OAEP_256;

50

public static final KeyAlgorithm<PublicKey, PrivateKey> ECDH_ES;

51

public static final KeyAlgorithm<PublicKey, PrivateKey> ECDH_ES_A128KW;

52

public static final KeyAlgorithm<PublicKey, PrivateKey> ECDH_ES_A192KW;

53

public static final KeyAlgorithm<PublicKey, PrivateKey> ECDH_ES_A256KW;

54

public static final KeyAlgorithm<Password, Password> PBES2_HS256_A128KW;

55

public static final KeyAlgorithm<Password, Password> PBES2_HS384_A192KW;

56

public static final KeyAlgorithm<Password, Password> PBES2_HS512_A256KW;

57

}

58

59

public static final class ZIP {

60

public static final CompressionAlgorithm DEF;

61

public static final CompressionAlgorithm GZIP;

62

}

63

}

64

```

65

66

## JWT Builder

67

68

The `JwtBuilder` interface provides a fluent API for constructing JWTs with various configurations.

69

70

### Basic JWT Builder Interface

71

72

```java { .api }

73

public interface JwtBuilder {

74

// Configuration

75

JwtBuilder provider(Provider provider);

76

JwtBuilder random(SecureRandom secureRandom);

77

78

// Content

79

JwtBuilder content(String content);

80

JwtBuilder content(byte[] content);

81

JwtBuilder content(InputStream content);

82

83

// Standard Claims

84

JwtBuilder issuer(String iss);

85

JwtBuilder subject(String sub);

86

JwtBuilder audience(String aud);

87

JwtBuilder audiences(String... audiences);

88

JwtBuilder expiration(Date exp);

89

JwtBuilder notBefore(Date nbf);

90

JwtBuilder issuedAt(Date iat);

91

JwtBuilder id(String jti);

92

93

// Custom Claims

94

JwtBuilder claim(String name, Object value);

95

96

// Security

97

JwtBuilder signWith(Key key);

98

<K extends Key> JwtBuilder signWith(K key, SecureDigestAlgorithm<? super K, ?> alg);

99

JwtBuilder encryptWith(SecretKey key, AeadAlgorithm enc);

100

<K extends Key> JwtBuilder encryptWith(K key, KeyAlgorithm<? super K, ?> keyAlg, AeadAlgorithm enc);

101

102

// Compression

103

JwtBuilder compressWith(CompressionAlgorithm alg);

104

105

// Access Builders

106

BuilderHeader header();

107

BuilderClaims claims();

108

109

// Build

110

String compact();

111

}

112

```

113

114

### Builder Helper Interfaces

115

116

```java { .api }

117

public interface BuilderClaims extends ClaimsBuilder<BuilderClaims> {

118

JwtBuilder and();

119

}

120

121

public interface BuilderHeader extends HeaderBuilder<BuilderHeader> {

122

JwtBuilder and();

123

}

124

```

125

126

### Usage Examples

127

128

#### Creating a Simple Signed JWT

129

130

```java

131

import io.jsonwebtoken.Jwts;

132

import io.jsonwebtoken.security.Keys;

133

import javax.crypto.SecretKey;

134

import java.util.Date;

135

136

// Generate key

137

SecretKey key = Keys.secretKeyFor(Jwts.SIG.HS256);

138

139

// Build JWT with standard claims

140

String jwt = Jwts.builder()

141

.subject("user123")

142

.issuer("myapp")

143

.audience("web-app")

144

.expiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour

145

.issuedAt(new Date())

146

.id(UUID.randomUUID().toString())

147

.claim("role", "admin")

148

.claim("permissions", Arrays.asList("read", "write"))

149

.signWith(key)

150

.compact();

151

```

152

153

#### Creating an Encrypted JWT

154

155

```java

156

import io.jsonwebtoken.Jwts;

157

import io.jsonwebtoken.security.Keys;

158

import javax.crypto.SecretKey;

159

160

// Generate encryption key

161

SecretKey encKey = Keys.secretKeyFor(Jwts.ENC.A256GCM);

162

163

// Build encrypted JWT

164

String jwe = Jwts.builder()

165

.subject("sensitive-user")

166

.claim("ssn", "123-45-6789")

167

.claim("salary", 150000)

168

.encryptWith(encKey, Jwts.ENC.A256GCM)

169

.compact();

170

```

171

172

#### Using Builder Helpers for Complex Headers/Claims

173

174

```java

175

String jwt = Jwts.builder()

176

.header()

177

.type("JWT")

178

.keyId("key-1")

179

.and()

180

.claims()

181

.subject("user123")

182

.issuer("myapp")

183

.add("custom", "value")

184

.and()

185

.signWith(key)

186

.compact();

187

```

188

189

## JWT Parser

190

191

The `JwtParserBuilder` and `JwtParser` interfaces provide comprehensive JWT parsing and validation capabilities.

192

193

### JWT Parser Builder Interface

194

195

```java { .api }

196

public interface JwtParserBuilder {

197

// Configuration

198

JwtParserBuilder unsecured();

199

JwtParserBuilder provider(Provider provider);

200

JwtParserBuilder clock(Clock clock);

201

JwtParserBuilder clockSkewSeconds(long seconds);

202

203

// Key Management

204

JwtParserBuilder verifyWith(SecretKey key);

205

JwtParserBuilder verifyWith(PublicKey key);

206

JwtParserBuilder decryptWith(SecretKey key);

207

JwtParserBuilder decryptWith(PrivateKey key);

208

JwtParserBuilder keyLocator(Locator<Key> keyLocator);

209

210

// Claim Validation

211

JwtParserBuilder requireId(String id);

212

JwtParserBuilder requireSubject(String subject);

213

JwtParserBuilder requireIssuer(String issuer);

214

JwtParserBuilder requireAudience(String audience);

215

JwtParserBuilder requireExpiration(Date expiration);

216

JwtParserBuilder requireNotBefore(Date notBefore);

217

JwtParserBuilder requireIssuedAt(Date issuedAt);

218

JwtParserBuilder require(String claimName, Object value);

219

220

// Algorithm Configuration

221

NestedCollection<AeadAlgorithm, JwtParserBuilder> enc();

222

NestedCollection<KeyAlgorithm<?, ?>, JwtParserBuilder> key();

223

NestedCollection<SecureDigestAlgorithm<?, ?>, JwtParserBuilder> sig();

224

NestedCollection<CompressionAlgorithm, JwtParserBuilder> zip();

225

226

// Build

227

JwtParser build();

228

}

229

```

230

231

### JWT Parser Interface

232

233

```java { .api }

234

public interface JwtParser {

235

// Utility

236

boolean isSigned(CharSequence compact);

237

238

// Generic Parsing

239

Jwt<?, ?> parse(CharSequence jwt);

240

241

// Unsecured JWT Parsing

242

Jwt<Header, byte[]> parseUnsecuredContent(CharSequence jwt);

243

Jwt<Header, Claims> parseUnsecuredClaims(CharSequence jwt);

244

245

// Signed JWT (JWS) Parsing

246

Jws<byte[]> parseSignedContent(CharSequence jws);

247

Jws<Claims> parseSignedClaims(CharSequence jws);

248

249

// RFC 7797 Unencoded Payload Support

250

Jws<byte[]> parseSignedContent(CharSequence jws, byte[] unencodedPayload);

251

Jws<Claims> parseSignedClaims(CharSequence jws, byte[] unencodedPayload);

252

253

// Encrypted JWT (JWE) Parsing

254

Jwe<byte[]> parseEncryptedContent(CharSequence jwe);

255

Jwe<Claims> parseEncryptedClaims(CharSequence jwe);

256

}

257

```

258

259

### Usage Examples

260

261

#### Basic JWT Parsing and Validation

262

263

```java

264

import io.jsonwebtoken.Jwts;

265

import io.jsonwebtoken.Claims;

266

import io.jsonwebtoken.Jws;

267

268

// Create parser with key and validation rules

269

JwtParser parser = Jwts.parser()

270

.verifyWith(key)

271

.requireIssuer("myapp")

272

.requireAudience("web-app")

273

.clockSkewSeconds(30) // Allow 30 seconds clock skew

274

.build();

275

276

// Parse and validate

277

try {

278

Jws<Claims> jws = parser.parseSignedClaims(jwtString);

279

Claims claims = jws.getPayload();

280

281

String subject = claims.getSubject();

282

String role = claims.get("role", String.class);

283

284

System.out.println("Successfully parsed JWT for: " + subject);

285

System.out.println("Role: " + role);

286

} catch (JwtException e) {

287

System.err.println("JWT validation failed: " + e.getMessage());

288

}

289

```

290

291

#### Dynamic Key Resolution

292

293

```java

294

// Custom key locator for multi-tenant scenarios

295

Locator<Key> keyLocator = new Locator<Key>() {

296

@Override

297

public Key locate(Header header) {

298

String keyId = header.getKeyId();

299

String issuer = ((Claims) header).getIssuer(); // If available

300

301

// Look up key based on kid and/or issuer

302

return keyService.getKey(keyId, issuer);

303

}

304

};

305

306

JwtParser parser = Jwts.parser()

307

.keyLocator(keyLocator)

308

.build();

309

```

310

311

#### Algorithm Restriction

312

313

```java

314

// Restrict to specific algorithms for security

315

JwtParser parser = Jwts.parser()

316

.verifyWith(publicKey)

317

.sig().add(Jwts.SIG.RS256).add(Jwts.SIG.RS384).and() // Only allow RS256/RS384

318

.build();

319

```

320

321

#### Parsing Encrypted JWTs

322

323

```java

324

JwtParser parser = Jwts.parser()

325

.decryptWith(privateKey)

326

.build();

327

328

try {

329

Jwe<Claims> jwe = parser.parseEncryptedClaims(jweString);

330

Claims claims = jwe.getPayload();

331

332

// Access sensitive data

333

String ssn = claims.get("ssn", String.class);

334

Integer salary = claims.get("salary", Integer.class);

335

} catch (JwtException e) {

336

System.err.println("JWE decryption failed: " + e.getMessage());

337

}

338

```

339

340

## Advanced Features

341

342

### RFC 7797 Unencoded Payload Support

343

344

JJWT supports RFC 7797 for JWS with unencoded (detached) payloads:

345

346

```java

347

// Create JWS with unencoded payload

348

byte[] payload = "sensitive payload data".getBytes(StandardCharsets.UTF_8);

349

350

String jws = Jwts.builder()

351

.content(payload)

352

.header()

353

.add("b64", false) // Indicate unencoded payload

354

.and()

355

.signWith(key)

356

.compact();

357

358

// Parse JWS with detached payload

359

Jws<byte[]> parsedJws = parser.parseSignedContent(jws, payload);

360

```

361

362

### Compression

363

364

JJWT supports payload compression to reduce JWT size:

365

366

```java

367

String compressedJwt = Jwts.builder()

368

.claim("data", largeDataObject)

369

.compressWith(Jwts.ZIP.DEF) // or Jwts.ZIP.GZIP

370

.signWith(key)

371

.compact();

372

373

// Decompression is automatic during parsing

374

Jws<Claims> jws = parser.parseSignedClaims(compressedJwt);

375

```

376

377

### Custom Clock for Testing

378

379

```java

380

// Use custom clock for deterministic testing

381

Clock fixedClock = new Clock() {

382

@Override

383

public Date now() {

384

return new Date(1609459200000L); // Fixed timestamp

385

}

386

};

387

388

JwtParser parser = Jwts.parser()

389

.verifyWith(key)

390

.clock(fixedClock)

391

.build();

392

```