An API that anyone can call without logging in is wide open. Django REST Framework’s TokenAuthentication fixes that in a few lines of config: the server issues each user a unique token, the client sends it in the Authorization header on every request, and DRF authenticates the user before the view runs. It fits best when the API serves a mobile app, an external script, or a third party — places where the browser session doesn’t work.
The Problem
Say you have a ViewSet returning a list of orders. By default, DRF enables no authentication — anyone who knows the URL can read the data, including sensitive data. SessionAuthentication forces clients outside the browser to deal with cookies and CSRF tokens, which is clumsy and a poor fit for mobile apps or automated scripts. You need something simpler: one fixed “key” per user, sent with every request, checked by the server — done.
# views.py — API đang mở toang: ai cũng gọi đượcfrom rest_framework import viewsetsfrom .models import Orderfrom .serializers import OrderSerializerclass OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer
The Solution
DRF ships TokenAuthentication out of the box, and it takes three steps. Step one: add rest_framework.authtoken to INSTALLED_APPS and run migrate — DRF creates the authtoken_token table that stores each user’s token. Step two: declare the default authentication class and require login for the whole API in settings. Step three: expose the token endpoint using the built-in obtain_auth_token view. From here, the client logs in once to get a token, then sends it in the Authorization header on every later request. Tokens live in the database, so they survive server restarts, and you can revoke a user’s access at any time just by deleting their token.
# settings.pyINSTALLED_APPS = [ ... "rest_framework", "rest_framework.authtoken",]REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ],}
# urls.pyfrom django.urls import pathfrom rest_framework.authtoken.views import obtain_auth_tokenurlpatterns = [ path("api-token-auth/", obtain_auth_token), # ... các URL khác]
# Lấy token (thay bằng username/password thật)curl -X POST -d "username=linh&password=mat-khau" \ http://127.0.0.1:8000/api-token-auth/# {"token": "9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"}# Gọi API kèm tokencurl -H "Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b" \ http://127.0.0.1:8000/api/orders/
If you want every user to have a token the moment they register, attach a post_save signal to the User model so a token is created automatically when a new account is created — no manual issuing one by one.
# accounts/signals.pyfrom django.conf import settingsfrom django.db.models.signals import post_savefrom django.dispatch import receiverfrom rest_framework.authtoken.models import Token@receiver(post_save, sender=settings.AUTH_USER_MODEL)def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)
Apply It to Your Project
Apply it right away to an internal API or one serving a mobile app: turn on TokenAuthentication for the whole API, and only open exceptions for public endpoints like registration with a per-view AllowAny permission. Remember two limits: the default token never expires, so it must travel over HTTPS to avoid being stolen in transit, and each user gets exactly one token — if you need expiring tokens or several tokens per device, switch to Simple JWT. Revoking a user’s access is just deleting their token in the admin or the shell.
Related Posts
- Django REST Framework: Filter, Search, and Sort Your API with django-filter in 5 Minutes
- Django signals: tự động tạo Profile cho user mới bằng post_save trong 5 phút
- Django REST Framework: Add Custom Endpoints with @action — No New ViewSet Needed in 5 Minutes
FAQ
How is TokenAuthentication different from SessionAuthentication?
SessionAuthentication uses cookies and a CSRF token, which suits web apps running in a browser. TokenAuthentication uses a fixed token string in the Authorization header, which suits mobile apps, scripts, and third parties because it doesn’t depend on browser cookies or sessions.
Does the token expire?
No. A DRF token lives forever until you delete it. If you want tokens that expire on their own, use djangorestframework-simplejwt or add an expiry field to a token model of your own.
Can one user have multiple tokens?
No, by default each user has exactly one token — Token has a OneToOne relationship with User. If you need several tokens for several devices, build your own token model or use Simple JWT with refresh tokens.
What if a token is lost?
Delete the old token in the Django admin or the shell and create a new one for that user — the old token stops working immediately. The client just logs in again to get a fresh token.
💬 Have you tried this in your own project? If you hit an error or know a shorter way, leave a comment below — I read them all and will add the good ideas to the post.
