or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

common-utilities.mddjango-integration.mdflask-integration.mdhttp-clients.mdindex.mdjose.mdoauth1.mdoauth2.mdoidc.md

jose.mddocs/

0

# JOSE Implementation

1

2

Complete implementation of JSON Object Signing and Encryption (JOSE) standards including JWT (RFC 7519), JWS (RFC 7515), JWE (RFC 7516), and JWK (RFC 7517). Provides both high-level JWT operations and low-level JOSE primitives with support for all standard algorithms.

3

4

## Capabilities

5

6

### JSON Web Token (JWT)

7

8

High-level JWT operations for creating and validating JSON Web Tokens with automatic header handling and claims validation.

9

10

```python { .api }

11

class JsonWebToken:

12

"""High-level JWT implementation with automatic algorithm detection."""

13

14

def __init__(self, algorithms: list = None, private_headers: set = None) -> None:

15

"""

16

Initialize JWT processor.

17

18

Args:

19

algorithms: List of allowed algorithms

20

private_headers: Set of private header names

21

"""

22

23

def encode(self, header: dict, payload: dict, key, check: bool = True) -> str:

24

"""

25

Encode a JWT token.

26

27

Args:

28

header: JWT header dictionary containing 'alg' and optional parameters

29

payload: JWT payload/claims dictionary

30

key: Signing key (string, RSA key, EC key, etc.)

31

check: Whether to validate header parameters

32

33

Returns:

34

JWT token string

35

"""

36

37

def decode(self, data: str, key, claims_cls=None, claims_options: dict = None, claims_params: dict = None) -> dict:

38

"""

39

Decode and validate a JWT token.

40

41

Args:

42

data: JWT token string

43

key: Verification key

44

claims_cls: Claims validation class

45

claims_options: Claims validation options

46

claims_params: Additional claims parameters

47

48

Returns:

49

Decoded payload dictionary

50

"""

51

52

# Pre-configured JWT instance with registered algorithms

53

jwt: JsonWebToken

54

```

55

56

### JSON Web Signature (JWS)

57

58

Low-level JWS operations for signing and verifying arbitrary payloads with full control over headers and serialization formats.

59

60

```python { .api }

61

class JsonWebSignature:

62

"""Low-level JWS implementation for signing arbitrary data."""

63

64

def __init__(self, algorithms: list = None, private_headers: set = None) -> None:

65

"""

66

Initialize JWS processor.

67

68

Args:

69

algorithms: List of allowed algorithms

70

private_headers: Set of private header names

71

"""

72

73

def serialize_compact(self, protected: dict, payload: bytes, key) -> str:

74

"""

75

Create a JWS compact serialization.

76

77

Args:

78

protected: Protected header dictionary

79

payload: Raw payload bytes

80

key: Signing key

81

82

Returns:

83

JWS compact serialization string

84

"""

85

86

def deserialize_compact(self, data: str, key, sender_key=None) -> dict:

87

"""

88

Deserialize and verify a JWS compact serialization.

89

90

Args:

91

data: JWS compact serialization string

92

key: Verification key

93

sender_key: Optional sender key for verification

94

95

Returns:

96

Dictionary with 'header' and 'payload' keys

97

"""

98

99

def serialize_json(self, payload: bytes, signatures: list) -> str:

100

"""

101

Create a JWS JSON serialization.

102

103

Args:

104

payload: Raw payload bytes

105

signatures: List of signature configurations

106

107

Returns:

108

JWS JSON serialization string

109

"""

110

111

class JWSAlgorithm:

112

"""Base class for JWS algorithms."""

113

114

name: str

115

description: str

116

117

def prepare_key(self, raw_data) -> Key:

118

"""Prepare and validate the signing key."""

119

120

def sign(self, bytestr: bytes, key: Key) -> bytes:

121

"""Sign the given bytes with the key."""

122

123

def verify(self, bytestr: bytes, signature: bytes, key: Key) -> bool:

124

"""Verify the signature against the bytes and key."""

125

```

126

127

### JSON Web Encryption (JWE)

128

129

JWE implementation for encrypting payloads with support for key encryption algorithms and content encryption algorithms.

130

131

```python { .api }

132

class JsonWebEncryption:

133

"""JWE implementation for encrypting JSON data."""

134

135

def __init__(self, algorithms: list = None, private_headers: set = None) -> None:

136

"""

137

Initialize JWE processor.

138

139

Args:

140

algorithms: List of allowed algorithms

141

private_headers: Set of private header names

142

"""

143

144

def serialize_compact(self, protected: dict, plaintext: bytes, recipient_key, sender_key=None) -> str:

145

"""

146

Create a JWE compact serialization.

147

148

Args:

149

protected: Protected header dictionary

150

plaintext: Raw plaintext bytes

151

recipient_key: Recipient's public key

152

sender_key: Optional sender's private key

153

154

Returns:

155

JWE compact serialization string

156

"""

157

158

def deserialize_compact(self, data: str, private_key, sender_key=None) -> dict:

159

"""

160

Deserialize and decrypt a JWE compact serialization.

161

162

Args:

163

data: JWE compact serialization string

164

private_key: Recipient's private key

165

sender_key: Optional sender's public key

166

167

Returns:

168

Dictionary with 'header' and 'payload' keys

169

"""

170

171

class JWEAlgorithm:

172

"""Base class for JWE key encryption algorithms."""

173

174

name: str

175

description: str

176

177

def prepare_key(self, raw_data) -> Key:

178

"""Prepare the key for encryption/decryption."""

179

180

def wrap(self, cek: bytes, key: Key, header: dict) -> tuple:

181

"""Wrap the Content Encryption Key."""

182

183

def unwrap(self, ek: bytes, key: Key, header: dict) -> bytes:

184

"""Unwrap the encrypted key to get CEK."""

185

186

class JWEEncAlgorithm:

187

"""Base class for JWE content encryption algorithms."""

188

189

name: str

190

description: str

191

192

def encrypt(self, plaintext: bytes, aad: bytes, iv: bytes, key: bytes) -> tuple:

193

"""Encrypt plaintext with additional authenticated data."""

194

195

def decrypt(self, ciphertext: bytes, aad: bytes, iv: bytes, tag: bytes, key: bytes) -> bytes:

196

"""Decrypt ciphertext and verify authentication tag."""

197

```

198

199

### JSON Web Key (JWK)

200

201

JWK implementation for representing cryptographic keys in JSON format with support for key operations and key sets.

202

203

```python { .api }

204

class JsonWebKey:

205

"""JWK implementation for key management."""

206

207

def __init__(self, algorithms: list = None) -> None:

208

"""

209

Initialize JWK processor.

210

211

Args:

212

algorithms: List of supported algorithms

213

"""

214

215

def import_key(self, raw_data, params: dict = None) -> Key:

216

"""

217

Import a key from various formats.

218

219

Args:

220

raw_data: Key data (PEM, DER, JWK dict, etc.)

221

params: Additional key parameters

222

223

Returns:

224

Key instance

225

"""

226

227

def export_key(self, key: Key) -> str:

228

"""

229

Export a key to JWK format.

230

231

Args:

232

key: Key instance to export

233

234

Returns:

235

JWK JSON string

236

"""

237

238

def import_key_set(self, data: dict) -> KeySet:

239

"""

240

Import a JWK Set.

241

242

Args:

243

data: JWK Set dictionary

244

245

Returns:

246

KeySet instance

247

"""

248

249

class Key:

250

"""Base class for cryptographic keys."""

251

252

kty: str # Key type

253

use: str # Key use

254

alg: str # Algorithm

255

kid: str # Key ID

256

257

def as_dict(self) -> dict:

258

"""Export key as dictionary."""

259

260

def as_json(self) -> str:

261

"""Export key as JSON string."""

262

263

def as_pem(self) -> bytes:

264

"""Export key as PEM format."""

265

266

class KeySet:

267

"""Container for multiple keys."""

268

269

def __init__(self, keys: list = None) -> None:

270

"""Initialize key set with optional keys list."""

271

272

def add_key(self, key: Key) -> None:

273

"""Add a key to the set."""

274

275

def find_by_kid(self, kid: str) -> Key:

276

"""Find key by key ID."""

277

278

def as_dict(self) -> dict:

279

"""Export key set as dictionary."""

280

```

281

282

### Key Types

283

284

Specific key implementations for different cryptographic algorithms.

285

286

```python { .api }

287

class RSAKey(Key):

288

"""RSA key implementation."""

289

290

def __init__(self, key_data: dict = None) -> None:

291

"""Initialize RSA key from key data dictionary."""

292

293

@classmethod

294

def generate_key(cls, key_size: int = 2048, auto_kid: bool = False) -> 'RSAKey':

295

"""Generate a new RSA key pair."""

296

297

class ECKey(Key):

298

"""Elliptic Curve key implementation."""

299

300

def __init__(self, key_data: dict = None) -> None:

301

"""Initialize EC key from key data dictionary."""

302

303

@classmethod

304

def generate_key(cls, crv: str = 'P-256', auto_kid: bool = False) -> 'ECKey':

305

"""Generate a new EC key pair."""

306

307

class OKPKey(Key):

308

"""Octet Key Pair for EdDSA."""

309

310

def __init__(self, key_data: dict = None) -> None:

311

"""Initialize OKP key from key data dictionary."""

312

313

@classmethod

314

def generate_key(cls, crv: str = 'Ed25519', auto_kid: bool = False) -> 'OKPKey':

315

"""Generate a new OKP key pair."""

316

317

class OctKey(Key):

318

"""Symmetric key implementation."""

319

320

def __init__(self, key_data: dict = None) -> None:

321

"""Initialize symmetric key from key data dictionary."""

322

323

@classmethod

324

def generate_key(cls, key_size: int = 256, auto_kid: bool = False) -> 'OctKey':

325

"""Generate a new symmetric key."""

326

```

327

328

### Claims Validation

329

330

JWT claims validation with support for standard and custom claims.

331

332

```python { .api }

333

class BaseClaims:

334

"""Base class for claims validation."""

335

336

def __init__(self, payload: dict, header: dict = None) -> None:

337

"""

338

Initialize claims validator.

339

340

Args:

341

payload: JWT payload dictionary

342

header: Optional JWT header dictionary

343

"""

344

345

def validate(self, now: int = None) -> None:

346

"""

347

Validate all claims.

348

349

Args:

350

now: Current timestamp for time-based validations

351

"""

352

353

class JWTClaims(BaseClaims):

354

"""Standard JWT claims validation."""

355

356

def validate_iss(self) -> None:

357

"""Validate issuer claim."""

358

359

def validate_sub(self) -> None:

360

"""Validate subject claim."""

361

362

def validate_aud(self) -> None:

363

"""Validate audience claim."""

364

365

def validate_exp(self, now: int = None, leeway: int = 0) -> None:

366

"""Validate expiration time claim."""

367

368

def validate_nbf(self, now: int = None, leeway: int = 0) -> None:

369

"""Validate not before claim."""

370

371

def validate_iat(self, now: int = None, leeway: int = 0) -> None:

372

"""Validate issued at claim."""

373

```

374

375

### Algorithm Registration

376

377

Functions to register standard and custom algorithms.

378

379

```python { .api }

380

def register_jws_rfc7518(cls: type) -> None:

381

"""

382

Register RFC 7518 JWS algorithms.

383

384

Args:

385

cls: JWS class to register algorithms on

386

"""

387

388

def register_jwe_rfc7518(cls: type) -> None:

389

"""

390

Register RFC 7518 JWE algorithms.

391

392

Args:

393

cls: JWE class to register algorithms on

394

"""

395

396

def register_jws_rfc8037(cls: type) -> None:

397

"""

398

Register RFC 8037 EdDSA algorithms.

399

400

Args:

401

cls: JWS class to register algorithms on

402

"""

403

```

404

405

## Error Handling

406

407

JOSE-specific error classes for different failure scenarios.

408

409

```python { .api }

410

class JoseError(AuthlibBaseError):

411

"""Base JOSE error."""

412

413

class DecodeError(JoseError):

414

"""Error decoding JOSE data."""

415

416

class MissingAlgorithmError(JoseError):

417

"""Algorithm not found or not supported."""

418

419

class UnsupportedAlgorithmError(JoseError):

420

"""Algorithm is not supported."""

421

422

class BadSignatureError(JoseError):

423

"""Invalid signature detected."""

424

425

class InvalidHeaderParameterNameError(JoseError):

426

"""Invalid header parameter name."""

427

428

class InvalidClaimError(JoseError):

429

"""Invalid claim value."""

430

431

class MissingClaimError(JoseError):

432

"""Required claim is missing."""

433

434

class InsecureClaimError(JoseError):

435

"""Claim contains insecure data."""

436

437

class ExpiredTokenError(JoseError):

438

"""Token has expired."""

439

440

class InvalidTokenError(JoseError):

441

"""Token is invalid."""

442

```

443

444

## Usage Examples

445

446

### Basic JWT Operations

447

448

```python

449

from authlib.jose import JsonWebToken, jwt

450

451

# Simple JWT with HMAC

452

token = jwt.encode({'alg': 'HS256'}, {'user': 'alice'}, 'secret')

453

payload = jwt.decode(token, 'secret')

454

455

# JWT with RSA key

456

from authlib.jose import RSAKey

457

458

rsa_key = RSAKey.generate_key(2048)

459

token = jwt.encode({'alg': 'RS256'}, {'user': 'alice'}, rsa_key)

460

payload = jwt.decode(token, rsa_key)

461

```

462

463

### JWS with Custom Payload

464

465

```python

466

from authlib.jose import JsonWebSignature

467

468

jws = JsonWebSignature()

469

header = {'alg': 'HS256'}

470

payload = b'custom data'

471

472

# Sign

473

token = jws.serialize_compact(header, payload, 'secret')

474

475

# Verify

476

data = jws.deserialize_compact(token, 'secret')

477

original_payload = data['payload']

478

```

479

480

### JWE Encryption

481

482

```python

483

from authlib.jose import JsonWebEncryption, RSAKey

484

485

jwe = JsonWebEncryption()

486

recipient_key = RSAKey.generate_key(2048)

487

488

# Encrypt

489

header = {'alg': 'RSA-OAEP', 'enc': 'A256GCM'}

490

token = jwe.serialize_compact(header, b'secret data', recipient_key)

491

492

# Decrypt

493

data = jwe.deserialize_compact(token, recipient_key)

494

plaintext = data['payload']

495

```