Django quickstart
By the end you will have a Django app with sign-in through authto.it, a protected /account page that shows
the signed-in person, and a sign-out that also ends the authto.it session. It uses
mozilla-django-oidc for the OpenID Connect parts and
Django's own user model and sessions to keep the person signed in. Tested with Python 3.12, Django 6.1.3 and
mozilla-django-oidc 5.0.2.
1. Create the site
On the authto.it dashboard, open your organization and choose Add site:
- Name: anything, for example My app (local).
- Return address:
http://localhost:8001/oidc/callback/(with the trailing slash) - After-sign-out address:
http://localhost:8001/ - Type: server-side (confidential). The site gets a client ID and a client secret. The secret is shown once, so copy it now.
A site can be invite-only (only the people you add can sign in) or open to anyone. Either works for this guide; on an invite-only site, add yourself first.
An AI tool connected to authto.it's MCP server can create the site for you, but the client secret is only issued on the dashboard.
2. Set up the project
mkdir my-app && cd my-app
python3 -m venv venv
. venv/bin/activate
pip install django mozilla-django-oidc
django-admin startproject mysite .
python manage.py startapp accounts
Create the environment file with your site's values. DJANGO_SECRET_KEY signs sessions and cookies; generate
one with python -c "import secrets; print(secrets.token_urlsafe(50))". Keep .env out of
version control.
.env
DJANGO_SECRET_KEY=change-me-to-a-long-random-string
AUTHTO_ISSUER=https://letme.authto.it
AUTHTO_CLIENT_ID=your-client-id
AUTHTO_CLIENT_SECRET=your-client-secret
Django doesn't read .env itself. This guide loads it into the shell before running
manage.py; in production, set the variables in the server's environment instead.
set -a; . ./.env; set +a
3. Add the code
mozilla-django-oidc provides three views under /oidc/: authenticate/ starts the sign-in with
PKCE, state and nonce; callback/ exchanges the code with the client secret and
verifies the ID token; logout/ ends the Django session and then sends the browser to authto.it to end
that session too. You add the settings, a user model with a role, a backend that keys people on sub, and
two pages.
Add this to the end of the generated settings file. It replaces the generated SECRET_KEY with the one from
the environment.
mysite/settings.py (append)
# --- authto.it sign-in -------------------------------------------------
import os
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
INSTALLED_APPS += [
"accounts",
"mozilla_django_oidc", # after django.contrib.auth
]
AUTH_USER_MODEL = "accounts.User"
AUTHENTICATION_BACKENDS = ["accounts.auth.AuthtoBackend"]
AUTHTO_ISSUER = os.environ.get("AUTHTO_ISSUER", "https://letme.authto.it")
# mozilla-django-oidc doesn't read discovery; these are the endpoints
# AUTHTO_ISSUER/.well-known/openid-configuration lists.
OIDC_OP_AUTHORIZATION_ENDPOINT = f"{AUTHTO_ISSUER}/authorize"
OIDC_OP_TOKEN_ENDPOINT = f"{AUTHTO_ISSUER}/token"
OIDC_OP_USER_ENDPOINT = f"{AUTHTO_ISSUER}/userinfo"
OIDC_OP_JWKS_ENDPOINT = f"{AUTHTO_ISSUER}/jwks.json"
OIDC_OP_LOGOUT_URL_METHOD = "accounts.auth.authto_logout_url"
OIDC_RP_CLIENT_ID = os.environ["AUTHTO_CLIENT_ID"]
OIDC_RP_CLIENT_SECRET = os.environ["AUTHTO_CLIENT_SECRET"]
OIDC_RP_SIGN_ALGO = "RS256" # keys from the JWKS endpoint
OIDC_RP_SCOPES = "openid email profile"
OIDC_USE_PKCE = True # S256
OIDC_USE_NONCE = True # the default; checked on the ID token
OIDC_STORE_ID_TOKEN = True # sent as id_token_hint on sign-out
LOGIN_URL = "oidc_authentication_init"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
The user model. Its username holds the ID token's sub, which never changes for a person on your
site. Email can change, and someone who signs in by text has none.
accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
# username holds authto.it's sub: permanent for a person on your site.
name = models.CharField(max_length=255, blank=True)
role = models.CharField(max_length=100, blank=True) # set on the dashboard
The backend and the sign-out address. The library checks the ID token's signature against authto.it's JWKS, its expiry and the nonce; the backend adds the issuer and audience checks, then creates or updates the user from the token's claims.
accounts/auth.py
from urllib.parse import urlencode
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from mozilla_django_oidc.auth import OIDCAuthenticationBackend
class AuthtoBackend(OIDCAuthenticationBackend):
def verify_token(self, token, **kwargs):
# The library checks the signature (JWKS), exp and nonce.
# Check the issuer and audience too.
claims = super().verify_token(token, **kwargs)
aud = claims.get("aud")
auds = aud if isinstance(aud, list) else [aud]
if claims.get("iss") != settings.AUTHTO_ISSUER:
raise SuspiciousOperation("ID token has the wrong issuer")
if settings.OIDC_RP_CLIENT_ID not in auds:
raise SuspiciousOperation("ID token has the wrong audience")
return claims
def get_userinfo(self, access_token, id_token, payload):
# The verified ID token already has sub, email, name and role.
return payload
def verify_claims(self, claims):
# Key people on sub: someone who signs in by phone has no email.
return "sub" in claims
def filter_users_by_claims(self, claims):
return self.UserModel.objects.filter(username=claims["sub"])
def create_user(self, claims):
user = self.UserModel(username=claims["sub"])
user.set_unusable_password()
return self.update_user(user, claims)
def update_user(self, user, claims):
user.email = claims.get("email", "")
user.name = claims.get("name", "")
user.role = claims.get("role", "")
user.save()
return user
def authto_logout_url(request):
# Called before the Django session ends, so the ID token is still there.
query = {"post_logout_redirect_uri": request.build_absolute_uri("/")}
id_token = request.session.get("oidc_id_token")
if id_token:
query["id_token_hint"] = id_token
else:
query["client_id"] = settings.OIDC_RP_CLIENT_ID
return f"{settings.AUTHTO_ISSUER}/logout?{urlencode(query)}"
accounts/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
def home(request):
return render(request, "home.html")
@login_required
def account(request):
return render(request, "account.html")
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
from accounts import views
urlpatterns = [
path("", views.home, name="home"),
path("account", views.account, name="account"),
# /oidc/authenticate/, /oidc/callback/ (the return address), /oidc/logout/
path("oidc/", include("mozilla_django_oidc.urls")),
path("admin/", admin.site.urls),
]
accounts/templates/home.html
<!doctype html>
<title>Home</title>
{% if user.is_authenticated %}
<p>Signed in as {{ user.name|default:user.email }}</p>
<p><a href="{% url 'account' %}">Account</a></p>
<form method="post" action="{% url 'oidc_logout' %}">
{% csrf_token %}
<button type="submit">Sign out</button>
</form>
{% else %}
<p><a href="{% url 'oidc_authentication_init' %}">Sign in</a></p>
{% endif %}
accounts/templates/account.html
<!doctype html>
<title>Account</title>
<table>
<tr><th>sub</th><td>{{ user.username }}</td></tr>
<tr><th>email</th><td>{{ user.email }}</td></tr>
<tr><th>name</th><td>{{ user.name }}</td></tr>
<tr><th>role</th><td>{{ user.role|default:"(none)" }}</td></tr>
</table>
<p><a href="{% url 'home' %}">Home</a></p>
Create the tables. Do this before the first migrate of a new project: Django can't switch to a custom user
model later without extra work.
python manage.py makemigrations accounts
python manage.py migrate
4. Try it
python manage.py runserver 8001
Open http://localhost:8001/ (use localhost, not
127.0.0.1: the return address must match exactly) and choose Sign in. You land on authto.it's
sign-in page with your site's name. Enter your email address, type the code you receive, and you're back on the home
page, signed in. /account shows your sub, email, name and
role. Sign out ends the Django session, passes through authto.it, and returns to the home page signed out.
If authto.it shows an error instead of the sign-in page, check that the return address on the site is exactly
http://localhost:8001/oidc/callback/.
5. Protect pages and use the role
@login_required sends signed-out visitors to sign-in (LOGIN_URL) and brings them back
afterwards. For class-based views, use LoginRequiredMixin. The role is whatever you set for the person
on the authto.it dashboard; it's empty if you set none. It's refreshed at every sign-in.
accounts/views.py
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
@login_required
def reports(request):
if request.user.role != "admin":
raise PermissionDenied # 403 for people signed in without the role
return render(request, "reports.html")
{% if user.role == "admin" %}
<a href="{% url 'reports' %}">Reports</a>
{% endif %}
Going live
- Add the production return address (
https://example.com/oidc/callback/) and after-sign-out address (https://example.com/) on the site. Each must match exactly. - Keep
AUTHTO_CLIENT_SECRETandDJANGO_SECRET_KEYin the server's environment, never in the code. - Serve the app over HTTPS. Set
DEBUG = False,ALLOWED_HOSTS,SESSION_COOKIE_SECURE = TrueandCSRF_COOKIE_SECURE = True. Behind a proxy that ends TLS, setSECURE_PROXY_SSL_HEADERso the return address the library builds starts withhttps://. - Add
offline_accesstoOIDC_RP_SCOPESfor a refresh token only if the app calls APIs on the person's behalf. Sign-in alone doesn't need it. - Manage people and their roles on the authto.it dashboard. On an invite-only site, only the people you add can sign in.