Skip to content

Commit 3dc670f

Browse files
guillaume-pujolguillp
authored andcommitted
document custom JWT headers
1 parent ae1dba3 commit 3dc670f

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

README.md

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,11 +303,52 @@ The same is true for JWS and JWE tokens.
303303

304304
### Headers are auto-generated
305305

306-
When signing a JWS, JWE or JWT, the headers are autogenerated by default, based on the used key.
306+
When signing a JWS, JWE or JWT, the headers are autogenerated by default, based on the used key and algorithm.
307307

308-
You may obviously add more custom headers {
308+
You may add your own custom headers using the `extra_headers` parameter, and/or set a custom `typ` header with the parameter of the same name:
309309

310-
### `Jwk` as thin wrappers around `cryptography` keys
310+
```python
311+
from jwskate import SymmetricJwk, Jwt
312+
313+
jwk = SymmetricJwk.from_bytes(b"T0t4llyR@nd0M", kid="symmetric_key1")
314+
jwt = Jwt.sign(
315+
claims={"my": "claims"},
316+
key=jwk,
317+
alg="HS256",
318+
typ="CustomJWT",
319+
extra_headers={"custom_header": "custom_value"},
320+
)
321+
print(jwt)
322+
# eyJhbGciOiJIUzI1NiIsImN1c3RvbV9oZWFkZXIiOiJjdXN0b21fdmFsdWUiLCJ0eXAiOiJDdXN0b21KV1QiLCJraWQiOiJzeW1tZXRyaWNfa2V5MSJ9.eyJteSI6ImNsYWltcyJ9.ZqCp8Crq-mdCXLoy5NiEdPTSUlIFEjrzexA6mKHrMAc
323+
print(jwt.headers)
324+
# {'alg': 'HS256', 'custom_header': 'custom_value', 'typ': 'CustomJWT', 'kid': 'symmetric_key1'}
325+
```
326+
327+
If, for testing purposes, you need to fully control which headers are included in the JWT, even if they are inconsistent,
328+
you can use `Jwt.sign_arbitrary()`:
329+
330+
```python
331+
from jwskate import SymmetricJwk, Jwt
332+
333+
jwk = SymmetricJwk.from_bytes(b"T0t4llyR@nd0M", kid="symmetric_key1")
334+
jwt = Jwt.sign_arbitrary(
335+
headers={
336+
"custom_header": "custom_value",
337+
"typ": "WeirdJWT",
338+
"kid": "R@nd0m_KID",
339+
"alg": "WeirdAlg",
340+
},
341+
claims={"my": "claims"},
342+
key=jwk,
343+
alg="HS256",
344+
)
345+
print(jwt)
346+
# eyJjdXN0b21faGVhZGVyIjoiY3VzdG9tX3ZhbHVlIiwidHlwIjoiV2VpcmRKV1QiLCJraWQiOiJSQG5kMG1fS0lEIiwiYWxnIjoiV2VpcmRBbGcifQ.eyJteSI6ImNsYWltcyJ9.bcTFqCSiVIbyJhxClgsBDIyhbvLXTOXOV55QGqo2mhw
347+
print(jwt.headers) # you asked for inconsistent headers, you have them:
348+
# {'custom_header': 'custom_value', 'typ': 'WeirdJWT', 'kid': 'R@nd0m_KID', 'alg': 'WeirdAlg'}
349+
```
350+
351+
### `Jwk` as thin wrapper around `cryptography` keys
311352

312353
`Jwk` keys are just _thin_ wrappers around keys from the `cryptography` module, or, in the case of symmetric keys,
313354
around `bytes`. But, unlike `cryptography`keys, they present a consistent interface for signature creation/verification,

0 commit comments

Comments
 (0)