Перейти к содержимому
Все статьи
Django

JWT-аутентификация в Django REST Framework: практическое руководство

Как настроить безопасную токен-аутентификацию с SimpleJWT, refresh-токенами и разумными настройками для продакшена.

Temurbek Murotov 1 мин чтения

Эта статья пока доступна только на английском языке.

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_blacklist and 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.

  • #django
  • #drf
  • #authentication
  • #security
Поделиться:

Похожие статьи

Есть идея проекта?

Давайте превратим её в надёжный продукт. Первая консультация и оценка — бесплатно.