Simple, modern JWT authentication for Django REST Framework with roles support
Project description
jwtguard
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 compliant —
sub,jti,iat,expclaims 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/jwtguard.git
cd jwtguard
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest
License
MIT — see LICENSE for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jwtguard-0.1.1.tar.gz.
File metadata
- Download URL: jwtguard-0.1.1.tar.gz
- Upload date:
- Size: 15.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
eba3e232e6ab256cc3083f3ad24920813ca56507de802a386d5131fdc22903f7
|
|
| MD5 |
7978168bb65036b71d31f0209cd9db9b
|
|
| BLAKE2b-256 |
7f91f43c6c3d1de7d4329a18a0de5ab6c847c9e5be7f4863cb29040639e27c51
|
Provenance
The following attestation bundles were made for jwtguard-0.1.1.tar.gz:
Publisher:
release.yml on fabianfalon/jwtguard
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
jwtguard-0.1.1.tar.gz -
Subject digest:
eba3e232e6ab256cc3083f3ad24920813ca56507de802a386d5131fdc22903f7 - Sigstore transparency entry: 1399483297
- Sigstore integration time:
-
Permalink:
fabianfalon/jwtguard@79bcc88b17aec0d28d7137c424541253b5459e64 -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/fabianfalon
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@79bcc88b17aec0d28d7137c424541253b5459e64 -
Trigger Event:
push
-
Statement type:
File details
Details for the file jwtguard-0.1.1-py3-none-any.whl.
File metadata
- Download URL: jwtguard-0.1.1-py3-none-any.whl
- Upload date:
- Size: 12.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
90cddbf3c85e10f418e1b216d44627c7e6a04f7605d8dba4332df9cc75387747
|
|
| MD5 |
295a7ac05994be7be85a5f89786ae54d
|
|
| BLAKE2b-256 |
137ac2a1c4f06cb9d56765debca24b7011666d1e8075c0ff7b7f0a8c60084ef1
|
Provenance
The following attestation bundles were made for jwtguard-0.1.1-py3-none-any.whl:
Publisher:
release.yml on fabianfalon/jwtguard
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
jwtguard-0.1.1-py3-none-any.whl -
Subject digest:
90cddbf3c85e10f418e1b216d44627c7e6a04f7605d8dba4332df9cc75387747 - Sigstore transparency entry: 1399483316
- Sigstore integration time:
-
Permalink:
fabianfalon/jwtguard@79bcc88b17aec0d28d7137c424541253b5459e64 -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/fabianfalon
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@79bcc88b17aec0d28d7137c424541253b5459e64 -
Trigger Event:
push
-
Statement type: