Skip to main content

Simple, modern JWT authentication for Django REST Framework with roles support

Project description

jwtguard

PyPI version Python versions Tests Coverage License: MIT

Simple, modern JWT authentication for Django REST Framework — with roles, refresh token rotation, and zero magic.

Built on top of PyJWT, fully compliant with RFC 7519.


Why jwtguard?

Most JWT libraries for Django are either abandoned, over-engineered, or hide too much behind configuration. This library gives you a working JWT auth workflow in minutes, with code you can actually read and understand.

  • Explicit over magic — no hidden middleware or monkey-patching
  • Role-based permissions baked in, sourced from Django Groups
  • Refresh token rotation with database-backed revocation
  • RFC 7519 compliantsub, jti, iat, exp claims out of the box
  • RS256 and HS256 support
  • Django 4.2+ and 5.x compatible

Installation

pip install jwtguard

For RS256 support (asymmetric keys):

pip install "jwtguard[crypto]"

Quick start

1. Add to INSTALLED_APPS

INSTALLED_APPS = [
    ...
    "jwtguard",
]

2. Run migrations

python manage.py migrate

3. Configure DRF

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "jwtguard.authentication.JWTAuthentication",
    ],
}

4. Add URLs

from django.urls import include, path

urlpatterns = [
    path("api/auth/", include("jwtguard.urls")),
]

That's it. You now have a working JWT auth workflow.


Usage

Authenticate

curl -X POST http://localhost:8000/api/auth/token/ \
  -H "Content-Type: application/json" \
  -d '{"username": "john", "password": "secret"}'
{
  "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Call a protected endpoint

curl http://localhost:8000/api/me/ \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Refresh the access token

curl -X POST http://localhost:8000/api/auth/token/refresh/ \
  -H "Content-Type: application/json" \
  -d '{"refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}'
{
  "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Logout (revoke refresh token)

curl -X POST http://localhost:8000/api/auth/token/logout/ \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{"refresh": "<refresh_token>"}'

Logout from all devices

curl -X POST http://localhost:8000/api/auth/token/logout/all/ \
  -H "Authorization: Bearer <access_token>"

Endpoints

Method Endpoint Description
POST /auth/token/ Obtain access + refresh tokens
POST /auth/token/refresh/ Rotate refresh token, get new access token
POST /auth/token/logout/ Revoke a specific refresh token
POST /auth/token/logout/all/ Revoke all sessions for the current user

Role-based permissions

Roles are sourced from Django's built-in Group model and embedded in the access token at login time.

from jwtguard.permissions import HasRole, HasAllRoles

class ReportView(APIView):
    permission_classes = [HasRole.require("analyst", "admin")]

    def get(self, request):
        ...

class BillingView(APIView):
    # user must have BOTH roles
    permission_classes = [HasAllRoles.require("finance", "admin")]

    def post(self, request):
        ...

You can also read roles directly from the token payload in your view:

def get(self, request):
    payload = request.auth  # dict with all JWT claims
    roles = payload.get("roles", [])

Configuration

All settings go under DRF_JWT in your settings.py. Every key is optional — the defaults are production-ready.

from datetime import timedelta

DRF_JWT = {
    # Token lifetimes
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=7),

    # Signing
    "ALGORITHM": "HS256",           # or "RS256"
    "SIGNING_KEY": SECRET_KEY,      # for RS256: your private key
    "VERIFYING_KEY": None,          # for RS256: your public key

    # Refresh token behavior
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,

    # Roles
    "ROLES_CLAIM": "roles",         # claim name in the token
    "ROLES_FROM": "groups",         # attribute on the User model

    # Header
    "AUTH_HEADER_PREFIX": "Bearer",

    # Multi-service / microservices (optional)
    "AUDIENCE": None,               # e.g. "my-api"
    "ISSUER": None,                 # e.g. "https://auth.example.com"

    # Custom claims (optional)
    "EXTRA_CLAIMS_CALLABLE": None,  # dotted path to a callable(user) -> dict
}

RS256 example

from pathlib import Path

DRF_JWT = {
    "ALGORITHM": "RS256",
    "SIGNING_KEY": Path("private.pem").read_text(),
    "VERIFYING_KEY": Path("public.pem").read_text(),
}

Custom claims

Add any extra claims to the access token without touching core claims (sub, jti, type, exp):

# myapp/tokens.py
def add_claims(user):
    return {"email": user.email, "tenant": user.org.slug}

# settings.py
DRF_JWT = {
    "EXTRA_CLAIMS_CALLABLE": "myapp.tokens.add_claims",
}

Audience and issuer (microservices)

When multiple services share a signing key, configure AUDIENCE and ISSUER to prevent a token issued for one service from being accepted by another:

DRF_JWT = {
    "AUDIENCE": "payments-service",
    "ISSUER": "https://auth.example.com",
}

Custom roles source

If your roles live somewhere other than Django Groups, point ROLES_FROM at any attribute or property on your User model:

# models.py
class User(AbstractUser):
    @property
    def role_names(self):
        return [self.role]  # your custom logic

# settings.py
DRF_JWT = {
    "ROLES_FROM": "role_names",
}

Token payload structure

{
  "sub": "42",
  "jti": "a3f8c2...",
  "roles": ["admin", "editor"],
  "type": "access",
  "iat": 1714300800,
  "exp": 1714301700
}

No PII is included by default. Use EXTRA_CLAIMS_CALLABLE to embed custom data.


Requirements

  • Python 3.10+
  • Django 4.2+
  • djangorestframework 3.14+
  • PyJWT 2.8+

Contributing

Contributions are welcome. Please open an issue before submitting a pull request for significant changes.

git clone https://github.com/fabianfalon/drf-jwt-auth.git
cd drf-jwt-auth
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest

License

MIT — see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jwtguard-0.1.0.tar.gz (15.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jwtguard-0.1.0-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

Details for the file jwtguard-0.1.0.tar.gz.

File metadata

  • Download URL: jwtguard-0.1.0.tar.gz
  • Upload date:
  • Size: 15.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for jwtguard-0.1.0.tar.gz
Algorithm Hash digest
SHA256 583ba86eb4a4efee3bb99429d8955986b2db00ecf8a381d471b5a9260eb42bfa
MD5 0a630cb5e20b71d3dfc105af59c373d6
BLAKE2b-256 d354336420a84b86c574c844e2d4fdb50a7ba3e4f1ae1f9969adcfdacb80d0a9

See more details on using hashes here.

Provenance

The following attestation bundles were made for jwtguard-0.1.0.tar.gz:

Publisher: release.yml on fabianfalon/jwtguard

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file jwtguard-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: jwtguard-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for jwtguard-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dde553890375cad00c2c60034e659d704aaa3d68c1c7664e8af8258e0c16a200
MD5 e2b60579762afa36a707eb5739dad784
BLAKE2b-256 412cd0973336d0c96e64be8bb90fe7fc412406bc3b39c1a374f4a01eca679ad8

See more details on using hashes here.

Provenance

The following attestation bundles were made for jwtguard-0.1.0-py3-none-any.whl:

Publisher: release.yml on fabianfalon/jwtguard

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page