Django Sesame

3.2.3 · active · verified Thu Apr 16

Django Sesame provides frictionless authentication for your Django project using "Magic Links". It generates URLs with embedded authentication tokens, allowing users to log in or access specific content without passwords or traditional sessions. The library supports various token-based authentication use cases and is actively maintained, with current version 3.2.3 compatible with recent Django and Python versions.

Common errors

Warnings

Install

Imports

Quickstart

To quickly integrate `django-sesame`, first configure your Django `settings.py` by adding `sesame.backends.ModelBackend` to `AUTHENTICATION_BACKENDS`. Then, define a URL route for `sesame.views.LoginView` in your `urls.py`. You can then generate magic links using `sesame.utils.get_query_string(user)` and send them to users. Visiting this link will log the user in. You can also configure `SESAME_MAX_AGE` for token lifetime and mark user passwords as unusable if they'll only use magic links.

import os
from django.contrib.auth import get_user_model
from django.urls import path
from sesame.views import LoginView
from sesame.utils import get_query_string

# --- Django settings.py (example additions) ---
# AUTHENTICATION_BACKENDS = [
#     'django.contrib.auth.backends.ModelBackend',
#     'sesame.backends.ModelBackend',
# ]
# # Optional: Configure token lifetime (e.g., 10 minutes for login by email)
# import datetime
# SESAME_MAX_AGE = datetime.timedelta(minutes=10)

# --- Your app's urls.py (example) ---
urlpatterns = [
    path("sesame/login/", LoginView.as_view(), name="sesame-login"),
]

# --- Example usage in a view or script ---
User = get_user_model()

# Create or get a user (e.g., for 'jane.doe@example.com')
try:
    user = User.objects.get(email="jane.doe@example.com")
except User.DoesNotExist:
    user = User.objects.create_user("jane.doe", "jane.doe@example.com", "password123")
    user.set_unusable_password() # If only using magic links, make password unusable
    user.save()

# Assuming a base URL like 'http://127.0.0.1:8000'
base_url = os.environ.get('DJANGO_BASE_URL', 'http://127.0.0.1:8000')
login_path = '/sesame/login/'

# Generate a magic link
magic_link = base_url + login_path + get_query_string(user)

print(f"Magic link for {user.email}: {magic_link}")

# To test, manually visit this link in a browser while logged out.

view raw JSON →