FusionAuth QuickStart for Python Django
On this page
This QuickStart explains how to add a login page and authentication to a website built with Django. You'll begin with a simple Django app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.
This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.
Prerequisites#
This QuickStart requires:
If you use macOS or Windows, you need one of the following container management tools:
- Docker Desktop
- OrbStack (to use OrbStack for
docker composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
Create a Simple Django App#
For this QuickStart, we'll use a Django app that reads and writes data to a text file:
-
Create a folder for the app and navigate into it:
$ mkdir django-quickstart && cd django-quickstart -
Create a virtual environment for the app's dependencies and activate it:
$ python3 -m venv .venv$ source .venv/bin/activateOn Windows, activate the virtual environment with
.venv\Scripts\activateinstead. -
Install dependencies:
$ pip install Django==6.1.3 -
Create a Django project named
notesin the current folder:$ django-admin startproject notes .This creates a
manage.pyfile and anotesfolder with the project's settings and URL configuration. -
Create the database tables Django uses for sessions and its other built-in apps:
$ python manage.py migrate -
In the
notesfolder, create a file namedviews.pywith the following contents:from pathlib import Path from django.shortcuts import redirect from django.template import RequestContext, Template from django.http import HttpResponse TARGET_FILE = Path(__file__).resolve().parent.parent / 'note.txt' # Ensure the file exists so we don't crash if not TARGET_FILE.exists(): TARGET_FILE.write_text('Hello! Edit this text.') # Simple HTML UI PAGE = Template(''' <!DOCTYPE html> <html> <head> <title>Text Editor</title> <style> body { font-family: sans-serif; margin: 40px; line-height: 1.6; } textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; } button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; } button:hover { background: #0056b3; } </style> </head> <body> <h1>Edit: {{ filename }}</h1> <form method="POST" action="/save"> {% csrf_token %} <textarea name="content">{{ content }}</textarea> <br> <button type="submit">Save Changes</button> </form> </body> </html> ''') def home(request): context = RequestContext(request, {'filename': TARGET_FILE.name, 'content': TARGET_FILE.read_text()}) return HttpResponse(PAGE.render(context)) def save(request): TARGET_FILE.write_text(request.POST['content']) return redirect('/') # Refresh the page to show updated contentThe form includes
{% csrf_token %}because Django rejects form submissions without a CSRF token. -
Replace the contents of
notes/urls.pywith the following code, which connects the URLs to the views:from django.urls import path from django.views.decorators.http import require_GET, require_POST from . import views urlpatterns = [ path('', require_GET(views.home)), path('save', require_POST(views.save)), ] -
Run the app:
$ python manage.py runserver 3000 -
Open the app at http://localhost:3000.
-
Replace the text area text with "Hello Django", then click the Save Changes button.
-
In a file browser or terminal, look in the
django-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Django". -
Congratulations, you have a working Django app that lets you edit a local text file through your web browser. Press Ctrl+C on your keyboard to stop the Django server.
Install and Run FusionAuth#
Before we can add authentication to our Django app, we need a local FusionAuth instance:
-
Open your container management tool (listed in the prerequisites above).
-
From the
django-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- username:
admin@example.com - password:
password
- username:
-
Navigate to Applications -> QuickStart App -> Edit -> OAuth . On this page, you can find your client ID, your client secret, and specify redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Django app with FusionAuth.
-
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Django app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
Add FusionAuth to the Django App#
Now that you have a working instance of FusionAuth and a working Django app, let's use FusionAuth to add login to your Django app:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thedjango-quickstartfolder that containsmanage.pyandnote.txt:$ cd .. -
Create a file named
.envwith the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production FUSIONAUTH_CALLBACK_URL=http://localhost:3000/oauth-callback -
Install the dependencies we'll need to authenticate with FusionAuth:
$ pip install Authlib==1.9.9 requests==2.34.2 python-dotenv==1.2.4Most importantly, we're adding Authlib, which handles communication with our FusionAuth instance (using Requests to make HTTP calls), and python-dotenv, which handles reading our configuration from the
.envfile we just created. -
Replace the contents of
notes/views.pywith the following code:import os from functools import wraps from pathlib import Path from urllib.parse import urlencode from django.shortcuts import redirect from django.template import RequestContext, Template from django.http import HttpResponse # auth dependencies from authlib.integrations.django_client import OAuth from dotenv import load_dotenv BASE_DIR = Path(__file__).resolve().parent.parent TARGET_FILE = BASE_DIR / 'note.txt' # Ensure the file exists so we don't crash if not TARGET_FILE.exists(): TARGET_FILE.write_text('Hello! Edit this text.') # read configuration from .env file load_dotenv(BASE_DIR / '.env') FUSIONAUTH_URL = 'http://localhost:9011' CLIENT_ID = os.environ['FUSIONAUTH_CLIENT_ID'] CLIENT_SECRET = os.environ['FUSIONAUTH_CLIENT_SECRET'] CALLBACK_URL = os.environ['FUSIONAUTH_CALLBACK_URL'] # tell authlib how to talk to fusionauth oauth = OAuth() oauth.register( 'fusionauth', client_id=CLIENT_ID, client_secret=CLIENT_SECRET, server_metadata_url=f'{FUSIONAUTH_URL}/.well-known/openid-configuration', client_kwargs={'scope': 'openid', 'code_challenge_method': 'S256'}, ) # require authentication to access def login_required(view): @wraps(view) def wrapped(request, *args, **kwargs): if 'user' not in request.session: return redirect('/login') return view(request, *args, **kwargs) return wrapped # Simple HTML UI PAGE = Template(''' <!DOCTYPE html> <html> <head> <title>Text Editor</title> <style> body { font-family: sans-serif; margin: 40px; line-height: 1.6; } textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; } button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; } button:hover { background: #0056b3; } .logout-btn { background: #dc3545; color: white; padding: 8px 15px; text-decoration: none; border-radius: 4px; float: right; } </style> </head> <body> <a href="/logout" class="logout-btn">Logout</a> <h1>Edit: {{ filename }}</h1> <form method="POST" action="/save"> {% csrf_token %} <textarea name="content">{{ content }}</textarea> <br> <button type="submit">Save Changes</button> </form> </body> </html> ''') # --- routes --- def login(request): return oauth.fusionauth.authorize_redirect(request, CALLBACK_URL) def oauth_callback(request): token = oauth.fusionauth.authorize_access_token(request) request.session['user'] = {'id': token['userinfo']['sub']} return redirect('/') def logout(request): # Clear the local Django session request.session.flush() # Redirect to FusionAuth to clear the SSO session return redirect(f'{FUSIONAUTH_URL}/oauth2/logout?' + urlencode({'client_id': CLIENT_ID})) @login_required def home(request): context = RequestContext(request, {'filename': TARGET_FILE.name, 'content': TARGET_FILE.read_text()}) return HttpResponse(PAGE.render(context)) @login_required def save(request): TARGET_FILE.write_text(request.POST['content']) return redirect('/') # Refresh the page to show updated contentThe new code connects the app to FusionAuth:
load_dotenv()reads the configuration from the.envfile.oauth.registertells Authlib how to talk to FusionAuth. It uses the client Id, client secret, and PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges., and finds the login and token endpoints in the OpenID Connect discovery document at/.well-known/openid-configuration. With PKCE, Authlib sends a code verifier when it exchanges the authorization code for tokens, so a stolen authorization code is useless on its own.- The
login_requireddecorator sends users who aren't logged in to/login. It's defined in this file, not Django's built-inlogin_required, which works with Django's own user accounts. - The
/loginroute callsauthorize_redirect, which sends the user to the FusionAuth login page. - The
/oauth-callbackroute callsauthorize_access_token, which exchanges the authorization code from FusionAuth for tokens and validates the ID tokenA JSON Web Token that contains information about the authenticated user.. The app then stores the user's Id in the Django session. - The
/logoutroute clears the Django session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too.
-
Replace the contents of
notes/urls.pywith the following code, which adds the/login,/oauth-callback, and/logoutroutes:from django.urls import path from django.views.decorators.http import require_GET, require_POST from . import views urlpatterns = [ path('', require_GET(views.home)), path('save', require_POST(views.save)), path('login', require_GET(views.login)), path('oauth-callback', require_GET(views.oauth_callback)), path('logout', require_GET(views.logout)), ] -
That's it! Your Django app should now use FusionAuth login. Run the app:
$ python manage.py runserver 3000 -
Open the app at http://localhost:3000.
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
Edit the text file from the safety of an authenticated Django app.
-
Click Logout. FusionAuth ends your session and sends you back to the login page.
Add Independent Notes for Each User#
To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- username:
admin@example.com - password:
password
- username:
-
Navigate to Applications -> QuickStart App -> Edit -> Registration .
- Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
- In the Registration field list, turn on the Enabled and Required switches for the following rows:
- Birthdate
- First name
- Last name
-
Click the Save button in the top right of the page to save your changes to self-service registration.
-
Navigate to Users -> Richard Hendricks -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Django app.
-
Replace the contents of
notes/views.pywith the following code, which requests theprofileandemailscopes, reads the user's name (first and last) and Id from the ID token, and stores each user's note in a separate file:import os from functools import wraps from pathlib import Path from urllib.parse import urlencode from django.shortcuts import redirect from django.template import RequestContext, Template from django.http import HttpResponse # auth dependencies from authlib.integrations.django_client import OAuth from dotenv import load_dotenv BASE_DIR = Path(__file__).resolve().parent.parent # set up a directory for multi-user files DATA_DIR = BASE_DIR / 'user_data' DATA_DIR.mkdir(exist_ok=True) # read configuration from .env file load_dotenv(BASE_DIR / '.env') FUSIONAUTH_URL = 'http://localhost:9011' CLIENT_ID = os.environ['FUSIONAUTH_CLIENT_ID'] CLIENT_SECRET = os.environ['FUSIONAUTH_CLIENT_SECRET'] CALLBACK_URL = os.environ['FUSIONAUTH_CALLBACK_URL'] # tell authlib how to talk to fusionauth oauth = OAuth() oauth.register( 'fusionauth', client_id=CLIENT_ID, client_secret=CLIENT_SECRET, server_metadata_url=f'{FUSIONAUTH_URL}/.well-known/openid-configuration', client_kwargs={'scope': 'openid profile email', 'code_challenge_method': 'S256'}, ) # require authentication to access def login_required(view): @wraps(view) def wrapped(request, *args, **kwargs): if 'user' not in request.session: return redirect('/login') return view(request, *args, **kwargs) return wrapped # helper to get specific user file def get_user_file(user_id): return DATA_DIR / f'note-{user_id}.txt' # Simple HTML UI PAGE = Template(''' <!DOCTYPE html> <html> <head> <title>Text Editor</title> <style> body { font-family: sans-serif; margin: 40px; line-height: 1.6; } textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; } button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; } button:hover { background: #0056b3; } .logout-btn { background: #dc3545; color: white; padding: 8px 15px; text-decoration: none; border-radius: 4px; float: right; } </style> </head> <body> <a href="/logout" class="logout-btn">Logout</a> <p style="float: right; margin-right: 20px;">Welcome, {{ name }}</p> <h1>Personal Note Editor</h1> <form method="POST" action="/save"> {% csrf_token %} <textarea name="content">{{ content }}</textarea> <br> <button type="submit">Save Changes</button> </form> </body> </html> ''') # --- routes --- def login(request): return oauth.fusionauth.authorize_redirect(request, CALLBACK_URL) def oauth_callback(request): token = oauth.fusionauth.authorize_access_token(request) # authlib validates the ID token and decodes its claims into userinfo userinfo = token['userinfo'] full_name = f"{userinfo.get('given_name', '')} {userinfo.get('family_name', '')}".strip() request.session['user'] = { 'id': userinfo['sub'], 'email': userinfo.get('email'), 'name': full_name or userinfo.get('email') or 'User', } return redirect('/') def logout(request): # Clear the local Django session request.session.flush() # Redirect to FusionAuth to clear the SSO session return redirect(f'{FUSIONAUTH_URL}/oauth2/logout?' + urlencode({ 'client_id': CLIENT_ID, 'post_logout_redirect_uri': 'http://localhost:3000/login', })) @login_required def home(request): user = request.session['user'] target_file = get_user_file(user['id']) # Ensure the file exists so we don't crash if not target_file.exists(): target_file.write_text(f"Hello {user['name']}!") context = RequestContext(request, {'name': user['name'], 'content': target_file.read_text()}) return HttpResponse(PAGE.render(context)) @login_required def save(request): get_user_file(request.session['user']['id']).write_text(request.POST['content']) return redirect('/') # Refresh the page to show updated contentAuthlib validates the ID token and decodes its claims into
token['userinfo'], so we don't need a separate JWT library. The logout route also passes apost_logout_redirect_uri, which sends the user back to the login page after FusionAuth ends their session. -
Open the app at http://localhost:3000. The Django development server reloads the changed file, so you don't need to restart it.
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
In a separate private/incognito window, open the app at http://localhost:3000.
-
Click Create an account and create an account using your personal email address, name, and birthdate.
-
Enjoy using your unique user note! You should see your name at the top of the page, and in the default note text.
Your Django app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for note-<id>.txt files in the user_data directory. To identify which note corresponds to which user, compare the id in the file name with the id field in the user's Source tab.
Summary#
In this QuickStart, FusionAuth handled login for your Django app:
- Authlib sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
- The
login_requireddecorator kept logged-out users away from the notes page. - The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
- FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.
Next Steps#
This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.
FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.