Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Advanced

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:

Python · editable

Protecting views

Python · editable

(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_required redirects anonymous users to the login page (/accounts/login/?next=… by default).
  • @permission_required(..., raise_exception=True) returns 403 instead.
  • For class-based views use LoginRequiredMixin and PermissionRequiredMixin.
  • 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", subclassing AbstractUser) 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:

Python · editable

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

  1. In Django, add a @login_required view at /orders/ and check it redirects to /accounts/login/?next=/orders/ when logged out.
  2. In FastAPI, add a role claim to the JWT and a require_role("admin") dependency factory.
  3. Make the FastAPI token expire after 1 second, wait 2 seconds with await asyncio.sleep(2), and check the error.
✎ Check your understanding

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?

← APIs with Django REST framework