In episode 7: ViewSets + routers — complete CRUD API we built a full API for Category and Transaction — but right now, anyone who knows the API address can read, edit, and delete your data. Episode 8 locks the whole API with JWT via the djangorestframework-simplejwt library: add register and login endpoints, issue access + refresh token pairs, and require authentication on every transaction API. By the end of this episode, only logged-in users can call the expense tracker API.
Why JWT for This Project?
DRF ships with TokenAuthentication, but those tokens are random strings stored in the database — the server must query the DB on every request, and you handle expiry and revocation yourself. JWT is a self-contained token: the server signs it with SECRET_KEY and verifies the signature without a DB lookup, with a short-lived access token plus a long-lived refresh token to mint new access tokens. For a personal expense app with its own frontend or mobile client, JWT is the cleanest, most standard choice.
Step 1 — Install and Configure
Install the library, create the accounts app, then add this configuration to settings:
pip install djangorestframework-simplejwt
# settings.pyfrom datetime import timedeltaREST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ),}SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=7), "ROTATE_REFRESH_TOKENS": True,}
Add accounts to INSTALLED_APPS. Setting DEFAULT_PERMISSION_CLASSES to IsAuthenticated means every API requires login by default — the register and login endpoints will be opened individually with AllowAny in a later step.
Step 2 — Registration API
DRF has no built-in register endpoint, so we write one ourselves: a CreateAPIView using Django’s default User model:
# accounts/serializers.pyfrom django.contrib.auth.models import Userfrom django.contrib.auth.password_validation import validate_passwordfrom rest_framework import serializersclass RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( write_only=True, validators=[validate_password] ) class Meta: model = User fields = ("username", "email", "password") def create(self, validated_data): user = User( username=validated_data["username"], email=validated_data.get("email", ""), ) user.set_password(validated_data["password"]) user.save() return user
# accounts/views.pyfrom rest_framework import genericsfrom rest_framework.permissions import AllowAnyfrom .serializers import RegisterSerializerclass RegisterView(generics.CreateAPIView): serializer_class = RegisterSerializer permission_classes = [AllowAny]
Note: you must use set_password() — never assign a plain-text password to user.password; Django won’t hash it and nobody will be able to log in.
Step 3 — Login and Token Refresh Endpoints
simplejwt provides the token-obtain and token-refresh views out of the box; you just declare the URLs:
# urls.py (project)from django.urls import path, includefrom rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView,)from accounts.views import RegisterViewurlpatterns = [ # ... existing URLs (admin, api/...) path("api/auth/register/", RegisterView.as_view(), name="register"), path("api/auth/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), path("api/auth/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),]
Step 4 — Lock Down the ViewSets from Episode 7
Because IsAuthenticated is now the global default, CategoryViewSet and TransactionViewSet automatically require the Authorization: Bearer <access_token> header. No code changes needed from episode 7 — that’s the payoff of centralized configuration.
Step 5 — Test the Full Flow with curl
# 1. Register (do it once)curl -X POST http://127.0.0.1:8000/api/auth/register/ \ -H "Content-Type: application/json" \ -d '{"username": "linh", "email": "linh@example.com", "password": "StrongPassword123!"}'# 2. Log in -> receive an access + refresh token paircurl -X POST http://127.0.0.1:8000/api/auth/token/ \ -H "Content-Type: application/json" \ -d '{"username": "linh", "password": "StrongPassword123!"}'# 3. Call an authenticated API (replace ACCESS_TOKEN with the real one)curl http://127.0.0.1:8000/api/transactions/ \ -H "Authorization: Bearer ACCESS_TOKEN"# 4. Access expired (30 minutes) -> use refresh to get a new access tokencurl -X POST http://127.0.0.1:8000/api/auth/token/refresh/ \ -H "Content-Type: application/json" \ -d '{"refresh": "REFRESH_TOKEN"}'
The standard flow: register once, log in to receive a token pair, call APIs with the Bearer token, and when access expires use refresh to mint a new one without re-entering the password. Enabling ROTATE_REFRESH_TOKENS also rotates the old refresh token on every refresh, reducing the risk of a stolen token being reused.
Apply It to Your Project
With this configuration you have a complete login backend for the expense app: the frontend keeps the access token in memory and calls the refresh endpoint itself when it gets a 401, while the backend needs no sessions. In episode 9, we’ll tighten one more notch: each user will only see and manage their own expense data with custom permissions.
Related Posts
- Building an Expense Tracker with Django #7: ViewSets + Routers — Complete CRUD API
- Building an Expense Tracker with Django #6: Serializers for Category and Transaction
- Building an Expense Tracker with Django #5: Writing Your First Model Tests (TestCase)
Frequently Asked Questions
How is JWT different from DRF’s built-in TokenAuthentication?
DRF tokens are random strings stored in the database; the server must hit the DB on every request and tokens don’t expire on their own. JWTs are self-contained with a signature, the server verifies them without a DB lookup, and they have a clear short-lived access + long-lived refresh scheme — a better fit for APIs serving mobile or SPA clients.
When the access token expires, must users log in again?
No. Call POST /api/auth/token/refresh/ with the refresh token to get a new access token. Only when the refresh token itself expires (7 days in this configuration) is a fresh login required.
Should I store JWT in localStorage?
Convenient but risky: XSS can steal the token. The safer approach: keep the access token in application memory (a JavaScript variable), and the refresh token in an httpOnly cookie set by the server — unreadable by JavaScript.
JWT is stateless — so how do you “log out”?
The server doesn’t store access tokens, so it can’t delete them; the standard approach is blacklisting the refresh token (enable the rest_framework_simplejwt.token_blacklist app) and letting the short-lived access token expire on its own. With a 30-minute access token, the post-logout risk window is acceptable for a personal app.
Do I need email verification on registration?
Not for a personal-use app like this series. When you open it to real users, add email verification (django-allauth) and rate-limit registrations to fight spam.
References
- djangorestframework-simplejwt documentation: https://django-rest-framework-simplejwt.readthedocs.io/
- DRF – Authentication: https://www.django-rest-framework.org/api-guide/authentication/
