1. Install dependencies
djangorestframework(if not already installed).djangorestframework-simplejwt(for JWT handling).
2. Update Django settings
- Add
rest_frameworktoINSTALLED_APPS. - Configure DRF default auth classes to use JWT:
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = ['rest_framework_simplejwt.authentication.JWTAuthentication']
3. Create login (token) endpoints
- Use
SimpleJWTbuilt-in views:/api/token/β returns access + refresh tokens./api/token/refresh/β returns new access token using refresh token.
4. Frontend (React) login flow
- React collects username/password.
- Sends
POSTrequest to/api/token/with JSON:
{ "username": "user", "password": "pass" }{ "access": "jwt-access-token", "refresh": "jwt-refresh-token" }- React stores tokens (in memory,
localStorage, or httpOnly cookies depending on security policy).
5. Protect backend routes
- Use DRF
@permission_classes([IsAuthenticated])on protected API views. - Requests must include:
Authorization: Bearer <access_token>-
Token refresh flow
Access tokens usually expire fast (e.g., 5 min). Use /api/token/refresh/ with the refresh token to get a new access token. React should handle refreshing tokens silently in the background.
-
Logout
No server-side logout with JWT (stateless). React just deletes stored tokens. (Optional) If you want server-side blacklist β enable SIMPLE_JWT[βBLACKLIST_AFTER_ROTATIONβ] and use blacklist app.
-
Testing
Test login with valid/invalid creds. Test calling a protected route with: No token β should be 401 Unauthorized. Expired token β should be 401. Valid token β should succeed.
π Thatβs the clean JWT pipeline:
React login form β POST /api/token/ β get JWTs β store token β
use Authorization header β refresh tokens β logout clears tokens