A clean and production-ready JWT-based authentication system built with Django REST Framework and djangorestframework-simplejwt
.
Supports login/logout, token blacklisting, refresh token rotation, and role-based API access (RBAC) — ideal for real-world apps like e-commerce platforms (e.g., Amazon, eBay).
- 🔐 JWT Authentication (Access & Refresh tokens)
- 🧠 Token Blacklisting on Logout
- 🔄 Token Refresh Endpoint
- 👤 Role-Based Permissions:
admin
,seller
,customer
- ✅ Protected APIs by role
- 📝 User Registration Endpoint
- ⚙️ Custom User Model (
CustomUser
)
- Python 3.x
- Django 4.x
- Django REST Framework
- djangorestframework-simplejwt
git clone https://github.com/Am-Issath/django-jwt-auth-starter.git
cd django-jwt-auth-starter
python -m venv venv
source venv/bin/activate # For Windows: venv\Scripts\activate
pip install -r requirements.txt
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
POST /api/token/
Content-Type: application/json
{
"username": "admin",
"password": "yourpassword"
}
{
"access": "access_token_here",
"refresh": "refresh_token_here",
"username": "admin",
"role": "admin"
}
POST /api/token/refresh/
Content-Type: application/json
{
"refresh": "<your_refresh_token>"
}
POST /api/logout/
Authorization: Bearer <access_token>
Content-Type: application/json
{
"refresh": "<refresh_token>"
}
POST /api/register/
Content-Type: application/json
{
"username": "johndoe",
"email": "[email protected]",
"password": "yourpass",
"role": "seller" # or 'admin' / 'customer'
}
GET /api/admin-only/
Authorization: Bearer <admin_access_token>
{
"message": "Hello, Admin!"
}
In settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ROTATE_REFRESH_TOKEN': True,
'BLACKLIST_AFTER_ROTATION': True,
'AUTH_HEADER_TYPES': ('Bearer',),
}
-
Login via /api/token/ to get access & refresh tokens.
-
Send access_token in every subsequent request header:
Authorization: Bearer <access_token>
-
When the access token expires, use the refresh_token at /api/token/refresh/ to obtain a new access token.
-
To logout: Call /api/logout/ with the refresh token in the request body.
The CustomUser model includes a role field (admin, seller, customer). Protected views leverage custom permissions: