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.timedeltaor a number of seconds.When
SESAME_MAX_AGEisNone, tokens always have an unlimited lifetime.When
SESAME_MAX_AGEis notNone, you can adjust the desired lifetime in any API that accepts amax_ageargument.Changing
SESAME_MAX_AGEdoesn’t always invalidate tokens.Changing the value of
SESAME_MAX_AGEdoesn’t invalidate tokens as long as it isn’tNone.The new value applies to all tokens, even those that were generated before the change.
Only switching it between
Noneand another value invalidates all tokens.
- SESAME_ONE_TIME = False¶
Set
SESAME_ONE_TIMEtoTrueto 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_CHANGEtoFalseto prevent this.
- SESAME_INVALIDATE_ON_EMAIL_CHANGE = False¶
Set
SESAME_INVALIDATE_ON_EMAIL_CHANGEtoTrueto 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
scopeto 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
dictof query string parameters to authenticateuser.Set
scopeto 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
scopeto 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.
AuthenticationMiddlewarerequires the optionaluaextra to prevent issues with Safari:$ pip install 'django-sesame[ua]'
In the
MIDDLEWAREsetting,"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
nextquery string parameter or thenext_pageattribute of the view.next_pagedefaults toLOGIN_REDIRECT_URL.If a
scopeattribute is set, a scoped token is expected.If a
max_ageattribute is set, override theSESAME_MAX_AGEsetting.In addition to
next_page,LoginViewalso supportsredirect_field_name,success_url_allowed_hosts, andget_default_redirect_url(). These APIs behave like their counterparts in Django’s built-inLoginView.
- @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.userin the view. Else,PermissionDeniedis raised, resulting in an HTTP 403 Forbidden error.authenticatemay be applied to a view directly:@authenticate def view(request): ...
or with arguments:
@authenticate(scope="status-page") def view(request): ...
If
scopeis set, a scoped token is expected.If
max_ageis set, override theSESAME_MAX_AGEsetting.Set
requiredtoFalseto setrequest.userto anAnonymousUserand execute the view when the token is invalid, instead of raising an exception. Then, you can check ifrequest.user.is_authenticated.authenticatedoesn’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
permanenttoTrueto calllogin()after a user is authenticated.authenticatedoesn’t care if a user is already logged in. It looks for a signed token anyway and overridesrequest.user.Set
overridetoFalseto 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_sesamemay be aHttpRequestcontaining a token in the URL or the token itself, created withget_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
scopeis set, a scoped token is expected.If
max_ageis set, override theSESAME_MAX_AGEsetting.If single-use tokens are enabled,
get_user()invalidates the token by updating the user’s last login date.Set
update_last_logintoTrueorFalseto 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 withlogin(), setupdate_last_logintoFalseto avoid updating the last login date twice.
Token customization¶
- class sesame.packers.BasePacker¶
Abstract base class for packers.
See Custom primary keys.
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
SesameBackendMixinand Django’s built-inModelBackend.Extending the default value of the
AUTHENTICATION_BACKENDSsetting 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_FIELDsetting.Return
Noneif 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
sesameis a valid token, return the user. Else, returnNone.If
scopeis set, a scoped token is expected.If
max_ageis set, override theSESAME_MAX_AGEsetting.requestis anHttpRequestorNone.