# Python JWT libraries

Python JWT libraries create, sign, and verify JSON Web Tokens, the signed tokens that carry identity claims between services. Libraries that implement the full JOSE standards also encrypt tokens and manage the keys that sign them. These libraries let APIs and AI agents check who sent each request.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [PyJWT](#pyjwt-library) | 761.0M | 5.7K | Sep 2026 | MIT |
| [Authlib](#authlib-library) | 137.9M | 5.5K | Nov 2026 | BSD-3-Clause |
| [joserfc](#joserfc) | 128.5M | 184 | Nov 2026 | BSD-3-Clause |
| [python-jose](#python-jose) | 31.8M | 1.8K | May 2025 | MIT |
| [JWCrypto](#jwcrypto) | 19.4M | 481 | Sep 2026 | LGPL-3.0-or-later |
| [jwt](#jwt) | 3.1M | 157 | Jun 2025 | Apache-2.0 |
| [jwskate](#jwskate) | 1.7M | 24 | Apr 2025 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[PyJWT](#pyjwt-library) has the most monthly downloads in this comparison, at 761.0M.

## Capabilities

| Library | JWE encryption | EdDSA signatures |
| --- | --- | --- |
| [PyJWT](#pyjwt-library) | No | Yes |
| [Authlib](#authlib-library) | Yes | Yes |
| [joserfc](#joserfc) | Yes | Yes |
| [python-jose](#python-jose) | Yes | No |
| [JWCrypto](#jwcrypto) | Yes | Yes |
| [jwt](#jwt) | No | No |
| [jwskate](#jwskate) | Yes | Yes |

## Libraries

### PyJWT

[GitHub](https://github.com/jpadilla/pyjwt) · [PyPI](https://pypi.org/project/pyjwt) · [Docs](https://pypi.org/project/pyjwt/)

Encodes and decodes JSON Web Tokens.

- Downloads / mo: 761.0M
- Stars: 5.7K
- Last release: 2.15.1
- License: MIT
- Capabilities: [From the PyJWT docs](https://pypi.org/project/pyjwt/)

```sh
pip install "PyJWT[crypto]"
```

**mozilla/mozilla-django-oidc** (560 stars)

[mozilla/mozilla-django-oidc](https://github.com/mozilla/mozilla-django-oidc) 

```python
def retrieve_matching_jwk(self, token):
    """Get the signing key by exploring the JWKS endpoint of the OP.

    Don't use jwt.PyJWKClient()get_signing_key_from_jwt() because it doesn't check
    the algorithm in case of multiple jwk with the same kid.
    """
    response_jwks = requests.get(
        self.OIDC_OP_JWKS_ENDPOINT,
        verify=self.get_settings("OIDC_VERIFY_SSL", True),
        timeout=self.get_settings("OIDC_TIMEOUT", None),
        proxies=self.get_settings("OIDC_PROXY", None),
    )
    response_jwks.raise_for_status()
    jwks = response_jwks.json()

    # Compute the current header from the given token to find a match
    jws = jwt.get_unverified_header(token)

    key = None
    for jwk in jwks["keys"]:
        if import_from_settings("OIDC_VERIFY_KID", True) and jwk[
            "kid"
        ] != smart_str(jws["kid"]):
            continue
        if "alg" in jwk and jwk["alg"] != smart_str(jws["alg"]):
            continue
        key = jwk
    if key is None:
        raise SuspiciousOperation("Could not find a valid JWKS.")
    return jwt.PyJWK(key)
```

[mozilla_django_oidc/auth.py](https://github.com/mozilla/mozilla-django-oidc/blob/86660c22c842d935551e3da7ab14709e53facd12/mozilla_django_oidc/auth.py#L151-L180) · [More projects using PyJWT →](https://dashboard.exa.ai/playground/search?q=pyjwt%20GitHub%20projects)

**Quickstart**

```python
import os
import jwt
token = jwt.encode({'sub': '123'}, os.environ['JWT_SECRET'], algorithm='HS256')

```

From [api.html](https://pyjwt.readthedocs.io/en/stable/api.html)

### Authlib

[GitHub](https://github.com/authlib/authlib) · [PyPI](https://pypi.org/project/authlib) · [Docs](https://docs.authlib.org/)

Builds OAuth and OpenID Connect servers and clients.

- Downloads / mo: 137.9M
- Stars: 5.5K
- Last release: 1.9.9
- License: BSD-3-Clause
- Capabilities: [From the Authlib docs](https://docs.authlib.org/)

```sh
pip install Authlib
```

**element-hq/synapse** (4.8K stars)

[element-hq/synapse](https://github.com/element-hq/synapse) 

```python
async def _verify_jwt(
    self,
    alg_values: list[str],
    token: str,
    claims_cls: type[C],
    claims_options: dict | None = None,
    claims_params: dict | None = None,
) -> C:
    """Decode and validate a JWT, re-fetching the JWKS as needed.

    Args:
        alg_values: list of `alg` values allowed when verifying the JWT.
        token: the JWT.
        claims_cls: the JWTClaims class to use to validate the claims.
        claims_options: dict of options passed to the `claims_cls` constructor.
        claims_params: dict of params passed to the `claims_cls` constructor.

    Returns:
        The decoded claims in the JWT.
    """
    jwt = JsonWebToken(alg_values)

    logger.debug("Attempting to decode JWT (%s) %r", claims_cls.__name__, token)

    # Try to decode the keys in cache first, then retry by forcing the keys
    # to be reloaded
    jwk_set = await self.load_jwks()
    try:
        claims = jwt.decode(
            token,
            key=jwk_set,
            claims_cls=claims_cls,
            claims_options=claims_options,
            claims_params=claims_params,
        )
    except ValueError:
        logger.info("Reloading JWKS after decode error")
        jwk_set = await self.load_jwks(force=True)  # try reloading the jwks
        claims = jwt.decode(
            token,
            key=jwk_set,
            claims_cls=claims_cls,
            claims_options=claims_options,
            claims_params=claims_params,
        )

    logger.debug("Decoded JWT (%s) %r; validating", claims_cls.__name__, claims)

    claims.validate(
        now=self._clock.time(), leeway=120
    )  # allows 2 min of clock skew
    return claims
```

[synapse/handlers/oidc.py](https://github.com/element-hq/synapse/blob/5ed830b3b4c74c89d876cc07756c5d98a100cbed/synapse/handlers/oidc.py#L958-L1009) · [More projects using Authlib →](https://dashboard.exa.ai/playground/search?q=authlib%20GitHub%20projects)

**Quickstart**

```python
from authlib.jose import jwt
with open('private.pem', 'rb') as key_file:
    token = jwt.encode({'alg': 'RS256'}, {'sub': '123'}, key_file.read())

```

From [jwt.html](https://docs.authlib.org/en/latest/jose/jwt.html)

### joserfc

[GitHub](https://github.com/authlib/joserfc) · [PyPI](https://pypi.org/project/joserfc) · [Docs](https://jose.authlib.org/)

Provides JOSE JWT encoding, decoding, and separate claim validation.

- Downloads / mo: 128.5M
- Stars: 184
- Last release: 1.8.0
- License: BSD-3-Clause
- Capabilities: [From the joserfc docs](https://jose.authlib.org/)

**Strengths**

- **Supports signed and encrypted JWTs.** Choose signed tokens or encrypted tokens through the JWT API.
- **Checks required and allowed claims.** Use JWTClaimsRegistry to require claims and restrict accepted values.
- **Replaces deprecated Authlib JOSE.** Use the separate JOSE library when migrating Authlib JWT code.

**Watch out for**

- **Decoding skips claim validation.** Validate token.claims separately with JWTClaimsRegistry.
- **Encryption needs its own registry.** Pass JWERegistry when encoding or decoding encrypted JWTs.

```sh
pip install joserfc
```

**authlib/authlib** (5.5K stars)

[authlib/authlib](https://github.com/authlib/authlib) 

```python
async def _decode_jwt(self, value, metadata, algorithms):
    """Decode a JWT signed with a key of the provider JWK set."""
    registry = JWSRegistry(algorithms=algorithms, strict_check_header=False)
    key_set = KeySet.import_key_set(await self.fetch_jwk_set())
    try:
        return jwt.decode(value, key=key_set, registry=registry)
    except InvalidKeyIdError:
        if metadata.get("jwks_uri") and not _may_refresh_jwk_set(self):
            raise

    key_set = KeySet.import_key_set(await self.fetch_jwk_set(force=True))
    return jwt.decode(value, key=key_set, registry=registry)
```

[authlib/integrations/base_client/async_openid.py](https://github.com/authlib/authlib/blob/549bda30e72d605673f065f4c44b2cead53c6621/authlib/integrations/base_client/async_openid.py#L49-L60) · [More projects using joserfc →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20joserfc%20for%20signed%20token%20verification%2C%20JWT%20claims%2C%20key%20selection%20and%20authentication%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from joserfc import jwt
from joserfc.jwk import OctKey
key = OctKey.generate_key()
token = jwt.encode({'alg': 'HS256'}, {'sub': '123'}, key)

```

From [jwt.md](https://jose.authlib.org/en/guide/jwt/)

### python-jose

[GitHub](https://github.com/mpdavis/python-jose) · [PyPI](https://pypi.org/project/python-jose) · [Docs](https://python-jose.readthedocs.io/en/latest/)

Implements JOSE signing, encryption, and key handling in Python.

- Downloads / mo: 31.8M
- Stars: 1.8K
- Last release: 3.5.0
- License: MIT
- Capabilities: [From the python-jose docs](https://python-jose.readthedocs.io/en/latest/)

**Strengths**

- **Signs and encrypts JOSE messages.** Use separate JWS and JWE APIs for signing and encryption.
- **Offers cryptographic backend choices.** Choose the cryptography, pycryptodome, or native Python backend.

**Watch out for**

- **Native backend cannot read certificates.** Use the cryptography backend when keys arrive as certificates.

```sh
pip install "python-jose[cryptography]"
```

**wecode-ai/Wegent** (888 stars)

[wecode-ai/Wegent](https://github.com/wecode-ai/Wegent) 

```python
def verify_token(token: str) -> Dict[str, Any]:
    """
    Verify token

    Args:
        token: Authentication token

    Returns:
        Data contained in the token

    Raises:
        HTTPException: Exception thrown when token is invalid
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
        )
        if not is_user_session_payload(payload):
            raise credentials_exception
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
        return {"username": token_data.username}
    except JWTError:
        raise credentials_exception
```

[backend/app/core/security.py](https://github.com/wecode-ai/Wegent/blob/4e3383794ad1ba8f3cfcbd7d316bf54604f454a6/backend/app/core/security.py#L264-L295) · [More projects using python-jose →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20python-jose%20for%20signed%20token%20verification%2C%20JWT%20claims%2C%20key%20selection%20and%20authentication%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import os
from jose import jwt
token = jwt.encode({'sub': '123'}, os.environ['JWT_SECRET'], algorithm='HS256')

```

From [README.rst](https://pypi.org/pypi/python-jose/3.5.0/json#info.description)

### JWCrypto

[GitHub](https://github.com/latchset/jwcrypto) · [PyPI](https://pypi.org/project/jwcrypto) · [Docs](https://pypi.org/project/jwcrypto/)

Creates signed or encrypted JSON Web Token objects.

- Downloads / mo: 19.4M
- Stars: 481
- Last release: 1.6.1
- License: LGPL-3.0-or-later
- Capabilities: [From the JWCrypto docs](https://pypi.org/project/jwcrypto/)

**Strengths**

- **Encrypts token payloads.** Create encrypted JWTs with make_encrypted_token().
- **Accepts JSON Web Key sets.** Pass a JWKSet when verification needs a set of candidate keys.

**Watch out for**

- **Missing expiry is accepted.** Set check_claims when expiration must be present.

```sh
pip install jwcrypto
```

**istio/istio** (38.5K stars)

[istio/istio](https://github.com/istio/istio) 

```python
def main(args):
    """Generates a signed JSON Web Token from local private key."""
    with open(args.key) as f:
        pem_data = f.read()
    f.closed

    pem_data_encode = pem_data.encode("utf-8")
    key = jwk.JWK.from_pem(pem_data_encode)

    if args.jwks:
        with open(args.jwks, "w+") as fout:
            fout.write("{ \"keys\":[ ")
            fout.write(key.export(private_key=False))
            fout.write("]}")
        fout.close

    now = int(time.time())
    payload = {
        # expire in one hour.
        "exp": now + args.expire,
        "iat": now,
    }
    if args.iss:
        payload["iss"] = args.iss
    if args.sub:
        payload["sub"] = args.sub
    else:
        payload["sub"] = args.iss

    if args.aud:
        if "," in args.aud:
            payload["aud"] = args.aud.split(",")
        else:
            payload["aud"] = args.aud

    if args.claims:
        for item in args.claims.split(","):
            k, v = item.split(':')
            payload[k] = v

    if args.listclaim:
        for item in args.listclaim:
            if (len(item) > 1):
                k = item[0]
                v = item[1:]
                payload[k] = v

    if args.nestedclaim:
        nested = {}
        for item in args.nestedclaim:
            if (len(item) > 1):
                k = item[0]
                v = item[1:]
                if len(v) == 1:
                    v = v[0]
                nested[k] = v
        nested["nested-2"] = copy.copy(nested)
        payload[args.nestedkey] = nested

    token = jwt.JWT(header={"alg": "RS256", "typ": "JWT", "kid": key.key_id},
                    claims=payload)

    token.make_signed_token(key)

    return token.serialize()
```

[security/tools/jwt/samples/gen-jwt.py](https://github.com/istio/istio/blob/3b89051c0e92164421bbc83c893e48b3bd0186ef/security/tools/jwt/samples/gen-jwt.py#L30-L94) · [More projects using JWCrypto →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20jwcrypto%20for%20signed%20token%20verification%2C%20JWT%20claims%2C%20key%20selection%20and%20authentication%20integrations&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from jwcrypto import jwk, jwt
key = jwk.JWK.generate(kty='oct', size=256)
token = jwt.JWT(header={'alg': 'HS256'}, claims={'sub': '123'})
token.make_signed_token(key)
serialized = token.serialize()

```

From [jwt.rst](https://jwcrypto.readthedocs.io/en/latest/jwt.html)

### jwt

[GitHub](https://github.com/GehirnInc/python-jwt) · [PyPI](https://pypi.org/project/jwt) · [Docs](https://pypi.org/project/jwt/)

Implements JSON Web Tokens.

- Downloads / mo: 3.1M
- Stars: 157
- Last release: 1.4.0
- License: Apache-2.0
- Capabilities: [From the jwt docs](https://pypi.org/project/jwt/)

```sh
pip install jwt
```

**unclecode/crawl4ai** (87.5K stars)

[unclecode/crawl4ai](https://github.com/unclecode/crawl4ai) 

```python
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """Create a JWT access token with an expiration."""
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
    to_encode.update({"exp": get_int_from_datetime(expire)})
    signing_key = get_jwk_from_secret(SECRET_KEY)
    return instance.encode(to_encode, signing_key, alg='HS256')
```

[deploy/docker/auth.py](https://github.com/unclecode/crawl4ai/blob/55de32d92594721e2ad4df59e74fe15769e0a978/deploy/docker/auth.py#L23-L29) · [More projects using jwt →](https://dashboard.exa.ai/playground/search?q=jwt%20GitHub%20projects)

**Quickstart**

```python
from jwt import JWT, jwk_from_pem
with open('private.pem', 'rb') as key_file:
    key = jwk_from_pem(key_file.read())
token = JWT().encode({'sub': '123'}, key, alg='RS256')

```

From [README.md](https://github.com/GehirnInc/python-jwt)

### jwskate

[GitHub](https://github.com/guillp/jwskate) · [PyPI](https://pypi.org/project/jwskate) · [Docs](https://pypi.org/project/jwskate/)

Implements the JOSE standards, including JWS, JWK, JWE, and JWT.

- Downloads / mo: 1.7M
- Stars: 24
- Last release: 0.12.2
- License: MIT
- Capabilities: [From the jwskate docs](https://pypi.org/project/jwskate/)

```sh
pip install jwskate
```

**Quickstart**

```python
from jwskate import Jwk, Jwt
key = Jwk.generate(alg='ES256')
token = Jwt.sign({'sub': '123'}, key)

```

From [README.md](https://guillp.github.io/jwskate/usage/) · [Find projects using jwskate →](https://dashboard.exa.ai/playground/search?q=jwskate%20GitHub%20projects)

## FAQ

### Which Python JWT library should I use?

[PyJWT](#pyjwt-library) suits applications that sign and verify tokens and fetch keys from a JWKS endpoint. [joserfc](#joserfc) and [JWCrypto](#jwcrypto) suit applications that also need encrypted tokens. [Authlib](#authlib-library) suits applications that build OAuth or OpenID Connect clients and servers alongside their token handling.

### What is PyJWT?

[PyJWT](#pyjwt-library) is a JSON Web Token implementation for Python that encodes and decodes signed tokens. Its PyJWKClient fetches signing keys from a JWKS endpoint.

### What is python-jose?

[python-jose](#python-jose) is a JOSE implementation that signs, encrypts, and handles keys. It runs on the cryptography package, PyCryptodome, or a native Python backend.

### What is joserfc?

[joserfc](#joserfc) implements the JOSE standards, including JWS, JWE, JWK, and JWT. It decodes a token and validates its claims as separate steps.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Python JWT libraries PyJWT python-jose Authlib jwcrypto joserfc code examples claim validation JWK encryption",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
