Skip to content

Commit

Permalink
document custom JWT headers
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaume-pujol authored and guillp committed Feb 1, 2024
1 parent ae1dba3 commit 3dc670f
Showing 1 changed file with 44 additions and 3 deletions.
47 changes: 44 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,52 @@ The same is true for JWS and JWE tokens.

### Headers are auto-generated

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

You may obviously add more custom headers {
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:

### `Jwk` as thin wrappers around `cryptography` keys
```python
from jwskate import SymmetricJwk, Jwt

jwk = SymmetricJwk.from_bytes(b"T0t4llyR@nd0M", kid="symmetric_key1")
jwt = Jwt.sign(
claims={"my": "claims"},
key=jwk,
alg="HS256",
typ="CustomJWT",
extra_headers={"custom_header": "custom_value"},
)
print(jwt)
# eyJhbGciOiJIUzI1NiIsImN1c3RvbV9oZWFkZXIiOiJjdXN0b21fdmFsdWUiLCJ0eXAiOiJDdXN0b21KV1QiLCJraWQiOiJzeW1tZXRyaWNfa2V5MSJ9.eyJteSI6ImNsYWltcyJ9.ZqCp8Crq-mdCXLoy5NiEdPTSUlIFEjrzexA6mKHrMAc
print(jwt.headers)
# {'alg': 'HS256', 'custom_header': 'custom_value', 'typ': 'CustomJWT', 'kid': 'symmetric_key1'}
```

If, for testing purposes, you need to fully control which headers are included in the JWT, even if they are inconsistent,
you can use `Jwt.sign_arbitrary()`:

```python
from jwskate import SymmetricJwk, Jwt

jwk = SymmetricJwk.from_bytes(b"T0t4llyR@nd0M", kid="symmetric_key1")
jwt = Jwt.sign_arbitrary(
headers={
"custom_header": "custom_value",
"typ": "WeirdJWT",
"kid": "R@nd0m_KID",
"alg": "WeirdAlg",
},
claims={"my": "claims"},
key=jwk,
alg="HS256",
)
print(jwt)
# eyJjdXN0b21faGVhZGVyIjoiY3VzdG9tX3ZhbHVlIiwidHlwIjoiV2VpcmRKV1QiLCJraWQiOiJSQG5kMG1fS0lEIiwiYWxnIjoiV2VpcmRBbGcifQ.eyJteSI6ImNsYWltcyJ9.bcTFqCSiVIbyJhxClgsBDIyhbvLXTOXOV55QGqo2mhw
print(jwt.headers) # you asked for inconsistent headers, you have them:
# {'custom_header': 'custom_value', 'typ': 'WeirdJWT', 'kid': 'R@nd0m_KID', 'alg': 'WeirdAlg'}
```

### `Jwk` as thin wrapper around `cryptography` keys

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

0 comments on commit 3dc670f

Please sign in to comment.