Django

Sign users in to a Django project with three views, Django's session, and PyJWT.

This guide adds sign-in to a Django project with three views and Django's own session. It reuses the four functions from the Python guide; put them in your application as onefold.py.

You need a confidential application with the redirect URI http://localhost:8000/auth/callback/. The trailing slash matters: redirect URIs match exactly. See Set up an application.

pip install requests "pyjwt[crypto]"

Views

myapp/views.py
import requests
from django.contrib.auth import get_user_model, login, logout
from django.http import HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.http import require_POST

from . import onefold


def sign_in(request):
    url, pending = onefold.start_sign_in()
    request.session["onefold_pending"] = pending
    return redirect(url)


def callback(request):
    pending = request.session.pop("onefold_pending", None)
    if request.GET.get("error"):
        return redirect(f"/?error={request.GET['error']}")
    if not pending or request.GET.get("state") != pending["state"]:
        return HttpResponseBadRequest("Invalid sign-in state")

    tokens = onefold.token_request(
        grant_type="authorization_code",
        code=request.GET.get("code", ""),
        redirect_uri=onefold.REDIRECT_URI,
        code_verifier=pending["verifier"],
    )
    claims = onefold.verify_id_token(tokens["id_token"], pending["nonce"])

    # Map the onefold user to a local user, keyed on `sub`.
    user, _ = get_user_model().objects.get_or_create(
        username=f"onefold:{claims['sub']}",
        defaults={"email": claims.get("email", "")},
    )
    login(request, user)
    request.session["onefold_refresh_token"] = tokens["refresh_token"]
    return redirect("/")


@require_POST
def sign_out(request):
    refresh_token = request.session.get("onefold_refresh_token")
    if refresh_token:
        requests.post(
            f"{onefold.ISSUER}/o/revoke_token/",
            data={
                "token": refresh_token,
                "client_id": onefold.CLIENT_ID,
                "client_secret": onefold.CLIENT_SECRET,
            },
            timeout=10,
        )
    logout(request)
    return redirect("/")

The local user is keyed on sub, not on email: a user can change their email address. The example stores sub in username to stay self-contained. In a real project, add a dedicated field or model for it.

URLs

myapp/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path("auth/sign-in/", views.sign_in, name="sign-in"),
    path("auth/callback/", views.callback, name="onefold-callback"),
    path("auth/sign-out/", views.sign_out, name="sign-out"),
]

Settings

Read the credentials from the environment, as onefold.py does:

ONEFOLD_CLIENT_ID=your-client-id
ONEFOLD_CLIENT_SECRET=your-client-secret
ONEFOLD_REDIRECT_URI=http://localhost:8000/auth/callback/

Django's default session backend stores data in the database, so the refresh token stays on your server.

logout ends the session in your application. The user stays signed in to onefold.

On this page