API reference#

Settings#

Changing settings invalidates all existing tokens.

The format of tokens depends on settings. As a consequence, changing any setting invalidates all existing tokens. There is a limited exception for SESAME_MAX_AGE.

For this reason, you should configure settings carefully before you start generating tokens.

SESAME_TOKEN_NAME = "sesame"#

Name of the query string parameter containing the authentication token.

SESAME_MAX_AGE = None#

Lifetime of authentications tokens, as a datetime.timedelta or a number of seconds.

When SESAME_MAX_AGE is None, tokens always have an unlimited lifetime.

When SESAME_MAX_AGE is not None, you can adjust the desired lifetime in any API that accepts a max_age argument.

Changing SESAME_MAX_AGE doesn’t always invalidate tokens.

Changing the value of SESAME_MAX_AGE doesn’t invalidate tokens as long as it isn’t None.

The new value applies to all tokens, even those that were generated before the change.

Only switching it between None and another value invalidates all tokens.

SESAME_ONE_TIME = False#

Set SESAME_ONE_TIME to True to invalidate tokens when they’re used.

Specifically, updating the user’s last login date invalidates tokens.

SESAME_INVALIDATE_ON_PASSWORD_CHANGE = True#

By default, tokens are invalidated when a user changes their password.

Set SESAME_INVALIDATE_ON_PASSWORD_CHANGE to False to prevent this.

SESAME_INVALIDATE_ON_EMAIL_CHANGE = False#

Set SESAME_INVALIDATE_ON_EMAIL_CHANGE to True to invalidate tokens when a user changes their email.

SESAME_PRIMARY_KEY_FIELD = "pk"#

Name of the field used as a primary key. See Custom primary keys.

SESAME_PACKER = None#

Dotted path to a built-in or custom packer. See Custom primary keys.

SESAME_TOKENS = ["sesame.tokens_v2", "sesame.tokens_v1"]#

Supported token formats. New tokens are generated with the first format. Existing tokens are accepted in any format listed here.

The default value means “generate tokens v2, accept tokens v2 and v1”. No other versions exist at this time.

SESAME_KEY = ""#

Change the value of this setting if you need to invalidate all tokens.

This setting only applies to tokens v2. See Tokens design.

SESAME_SIGNATURE_SIZE = 10#

Size of the signature in bytes.

This setting only applies to tokens v2. See Tokens design.

SESAME_SALT = "sesame"#

Change the value of this setting if you need to invalidate all tokens.

This setting only applies to tokens v1. See Tokens design.

Token generation#

django-sesame provides three utility functions for generating tokens, according to the context.

sesame.utils.get_query_string(user, scope='')#

Generate a complete query string to authenticate user.

Set scope to create a scoped token.

Use this function to add authentication to a URL that doesn’t contain a query string.

sesame.utils.get_parameters(user, scope='')#

Generate a dict of query string parameters to authenticate user.

Set scope to create a scoped token.

Use this function to add authentication to a URL that already contains a query string.

sesame.utils.get_token(user, scope='')#

Generate a signed token to authenticate user.

Set scope to create a scoped token.

Use this function to create a token that get_user() will accept.

Token validation#

django-sesame provides high-level APIs to authenticate a user or to log them in permanently.

class sesame.middleware.AuthenticationMiddleware(get_response)#

Look for a signed token in the URL of any request and log a user in.

After login, remove the token from the URL with an HTTP redirect.

This functionality requires additional setup for Safari.

AuthenticationMiddleware requires the optional ua extra to prevent issues with Safari:

$ pip install 'django-sesame[ua]'

In the MIDDLEWARE setting, "sesame.middleware.AuthenticationMiddleware" should be placed just after "django.contrib.auth.middleware.AuthenticationMiddleware":

MIDDLEWARE = [
    ...,
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "sesame.middleware.AuthenticationMiddleware",
    ...,
]
class sesame.views.LoginView(**kwargs)#

Look for a signed token in the URL of a GET request and log a user in.

If a valid token is found, the user is redirected to the URL specified in the next query string parameter or the next_page attribute of the view. next_page defaults to LOGIN_REDIRECT_URL.

If a scope attribute is set, a scoped token is expected.

If a max_age attribute is set, override the SESAME_MAX_AGE setting.

In addition to next_page, LoginView also supports redirect_field_name, success_url_allowed_hosts, and get_default_redirect_url(). These APIs behave like their counterparts in Django’s built-in LoginView.

@sesame.decorators.authenticate(view=None, scope='', max_age=None, *, required=True, permanent=False, override=True)#

Decorator that looks for a signed token in the URL and authenticates a user.

If a valid token is found, the user is available as request.user in the view. Else, PermissionDenied is raised, resulting in an HTTP 403 Forbidden error.

authenticate may be applied to a view directly:

@authenticate def view(request):
    ...

or with arguments:

@authenticate(scope="status-page")
def view(request):
    ...

If scope is set, a scoped token is expected.

If max_age is set, override the SESAME_MAX_AGE setting.

Set required to False to set request.user to an AnonymousUser and execute the view when the token is invalid, instead of raising an exception. Then, you can check if request.user.is_authenticated.

authenticate doesn’t log the user in permanently. It is intended to provide direct access to a specific resource without exposing all other private resources. This makes it more acceptable to use the less secure authentication mechanism provided by django-sesame.

Set permanent to True to call login() after a user is authenticated.

authenticate doesn’t care if a user is already logged in. It looks for a signed token anyway and overrides request.user.

Set override to False to skip authentication if a user is already logged in.

django-sesame also provides a low-level utility function for validating tokens.

sesame.utils.get_user(request_or_sesame, scope='', max_age=None, *, update_last_login=None)#

Authenticate a user based on a signed token.

request_or_sesame may be a HttpRequest containing a token in the URL or the token itself, created with get_token(). The latter supports use cases outside the HTTP request lifecycle.

If a valid token is found, return the user. Else, return None.

get_user() doesn’t log the user in permanently.

If scope is set, a scoped token is expected.

If max_age is set, override the SESAME_MAX_AGE setting.

If single-use tokens are enabled, get_user() invalidates the token by updating the user’s last login date.

Set update_last_login to True or False to always or never update the user’s last login date, regardless of whether single-use tokens are enabled. Typically, if you’re going to log the user in with login(), set update_last_login to False to avoid updating the last login date twice.

Token customization#

class sesame.packers.BasePacker#

Abstract base class for packers.

See Custom primary keys.

pack_pk(user_pk)#

Create a short representation of the primary key of a user.

Return bytes.

unpack_pk(data)#

Extract the primary key of a user from a signed token.

data contains bytes.

Return the primary key and the remaining data as bytes.

Authentication backend#

django-sesame requires configuring a compatible authentication backend in AUTHENTICATION_BACKENDS.

class sesame.backends.ModelBackend#

Authentication backend that authenticates users with django-sesame tokens.

It inherits SesameBackendMixin and Django’s built-in ModelBackend.

Extending the default value of the AUTHENTICATION_BACKENDS setting to add "sesame.backends.ModelBackend" looks like:

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "sesame.backends.ModelBackend",
]
get_user(user_id)#

Fetch user from the database by primary key.

The field used by django-sesame as a primary key can be configured with the SESAME_PRIMARY_KEY_FIELD setting.

Return None if no active user is found.

class sesame.backends.SesameBackendMixin#

Mix this class in an authentication backend providing get_user(user_id) to create an authentication backend usable with django-sesame.

authenticate(request, sesame, scope='', max_age=None)#

If sesame is a valid token, return the user. Else, return None.

If scope is set, a scoped token is expected.

If max_age is set, override the SESAME_MAX_AGE setting.

request is an HttpRequest or None.