Django REST Framework’da JWT autentifikatsiya: amaliy qo‘llanma
SimpleJWT, refresh tokenlar va production uchun to‘g‘ri sozlamalar bilan xavfsiz token autentifikatsiyasini qanday sozlash.
Bu maqola hozircha faqat ingliz tilida mavjud.
Token authentication is the default choice for APIs consumed by mobile apps and SPAs. In this guide we'll set up JWT authentication in Django REST Framework using djangorestframework-simplejwt.
1. Install the package
pip install djangorestframework-simplejwt
2. Configure DRF
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework_simplejwt.authentication.JWTAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
}
from datetime import timedelta
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
"REFRESH_TOKEN_LIFETIME": timedelta(days=7),
"ROTATE_REFRESH_TOKENS": True,
"BLACKLIST_AFTER_ROTATION": True,
}
Short-lived access tokens limit the damage if a token leaks. Rotating refresh tokens with a blacklist means a stolen refresh token can only be used once.
3. Add the URLs
# urls.py
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path("api/token/", TokenObtainPairView.as_view()),
path("api/token/refresh/", TokenRefreshView.as_view()),
]
4. Production checklist
- Always serve the API over HTTPS.
- Keep access tokens short-lived (5–15 minutes).
- Enable
rest_framework_simplejwt.token_blacklistand run migrations. - Add rate limiting to the token endpoint (
DEFAULT_THROTTLE_RATES). - Never log tokens.
With these defaults you get a secure, stateless authentication layer that scales well and is easy for frontend and mobile developers to use.