Works like standard Django — via a session cookie. Suitable for browser-based clients.
Authentication Types
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
}
Session Authentication
Works like standard Django — via a session cookie. Suitable for browser-based clients.
class TaskViewSet(viewsets.ModelViewSet):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
Token Authentication
Tokens are stored in the database and sent in the Authorization: Token <key> header. For full details — setup, endpoints, auto-creation via signals, and a custom login view — see Token Authentication in DRF.
JWT (JSON Web Tokens)
pip install djangorestframework-simplejwt
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view()),
path('api/token/refresh/', TokenRefreshView.as_view()),
]
Different Authentication for Different ViewSets
class PublicViewSet(viewsets.ReadOnlyModelViewSet):
authentication_classes = []
permission_classes = [AllowAny]
class PrivateViewSet(viewsets.ModelViewSet):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!