Authentication in Django and FastAPI
Both frameworks take very different approaches to logging users in. Django includes a complete, battle-tested system: user model, password hashing, sessions, login views, permissions and groups. FastAPI gives you security building blocks (OAuth2 schemes, dependencies) and you assemble a token-based login yourself. This lesson does both.
The Authentication & Security track explains the concepts behind this lesson: password hashing, sessions vs tokens, JWTs and OAuth.
Django's auth system
django.contrib.auth provides the User model, secure password hashing (PBKDF2 with hundreds of thousands of iterations by default; Argon2 and scrypt are available), sessions, and permissions:
Protecting views
(Django logs refused requests such as "Forbidden (Permission denied)", with a traceback, to the console. That's normal, and it's useful when debugging.)
@login_requiredredirects anonymous users to the login page (/accounts/login/?next=…by default).@permission_required(..., raise_exception=True)returns 403 instead.- For class-based views use
LoginRequiredMixinandPermissionRequiredMixin. - Django ships ready-made views for login, logout, password change and password reset by email (
django.contrib.auth.urls). Use them. - Start every project with a custom user model (
AUTH_USER_MODEL = "accounts.User", subclassingAbstractUser) so you can add fields later; changing it afterwards is painful.
Popular additions: django-allauth (social login, email verification, MFA, passkeys) and SimpleJWT for token auth in DRF.
FastAPI: OAuth2 password flow with JWT
FastAPI's security tools are dependencies. The classic setup: a /token endpoint takes a username and password (as a form, per the OAuth2 spec) and returns a JWT; protected routes depend on get_current_user, which validates the token from the Authorization: Bearer header:
Because OAuth2PasswordBearer is declared, the "Authorize" button in /docs works too: you can log in and call protected routes from the browser.
For production, consider an identity provider (Auth0, Keycloak, Cognito, Clerk) and validate their tokens, or a library such as FastAPI Users or AuthX; and use pwdlib (Argon2) for password hashing.
Practice
- In Django, add a
@login_requiredview at/orders/and check it redirects to/accounts/login/?next=/orders/when logged out. - In FastAPI, add a
roleclaim to the JWT and arequire_role("admin")dependency factory. - Make the FastAPI token expire after 1 second, wait 2 seconds with
await asyncio.sleep(2), and check the error.
1.What does Django's login(request, user) do?
2.In FastAPI, where does OAuth2PasswordBearer look for the token?
3.Why should a new Django project define a custom user model from the start?