💻 Примеры: BasicAuth, TokenAuth, JWT

⚡ Три примера в трёх строках

# BasicAuth — в settings.py
'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.BasicAuthentication']

# TokenAuth — в settings.py + в urls.py
path('api-token-auth/', obtain_auth_token)

# JWT — в settings.py + в urls.py
path('api/token/', TokenObtainPairView.as_view())

Пример 1: BasicAuthentication — полная настройка

settings.py

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

views.py — применение к представлению

# views.py
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import ListCreateAPIView

class ProductListCreateView(ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    authentication_classes = [BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ProductSerializer
        return ProductCreateUpdateSerializer

Тестирование в Postman

Вкладка Authorization → тип Basic Auth → ввести Username и Password. Postman автоматически кодирует строку в Base64 и добавляет заголовок.

Или вручную через URL: http://username:password@127.0.0.1:8000/products/

Пример 2: TokenAuthentication — полная настройка

settings.py

# settings.py
INSTALLED_APPS = [
    # ...
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

Миграции (обязательно)

python manage.py migrate

urls.py — маршрут для получения токена

# urls.py
from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]

views.py — применение к представлению

# views.py
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class ProductListCreateView(ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ProductSerializer
        return ProductCreateUpdateSerializer

Тестирование в Postman

  1. POST на http://127.0.0.1:8000/api-token-auth/ с body: {"username": "user", "password": "pass"}
  2. Получаем ответ: {"token": "9944b09199c62bcf..."}
  3. В заголовке следующего запроса: Authorization: Token 9944b09199c62bcf...

Пример 3: JWTAuthentication (SimpleJWT) — полная настройка

Установка

pip install djangorestframework-simplejwt

settings.py

# settings.py
from datetime import timedelta

INSTALLED_APPS = [
    # ...
    'rest_framework_simplejwt',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}

urls.py — маршруты JWT

# urls.py
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

views.py — применение к представлению Order

# views.py
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated

class OrderListCreateView(ListCreateAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return OrderSerializer
        return OrderCreateUpdateSerializer

Тестирование в Postman

  1. POST на http://127.0.0.1:8000/api/token/ с body: {"username": "user", "password": "pass"}
  2. Получаем: {"access": "eyJ...", "refresh": "eyJ..."}
  3. В заголовке: Authorization: Bearer eyJ...
  4. Когда access истёк — POST на /api/token/refresh/ с {"refresh": "eyJ..."}

Пример 4: Разрешения на уровне представления

# views.py
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAdminUser

# Только аутентифицированные могут изменять данные ProductDetail
class ProductDetailDetailUpdateDeleteView(RetrieveUpdateDestroyAPIView):
    queryset = ProductDetail.objects.all()
    serializer_class = ProductDetailSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ProductDetailSerializer
        return ProductDetailCreateUpdateSerializer

# Только администраторы могут управлять поставщиками
class SupplierViewSet(viewsets.ModelViewSet):
    queryset = Supplier.objects.all()
    serializer_class = SupplierSerializer
    permission_classes = [IsAdminUser]
← К оглавлению урока    Задания →