This package provides a lightweight extension to the included token authentication in Django Rest Framework, causing tokens to expire after a specified duration.
This behaviour is good practice when using token authentication for production APIs. If you require more complex token functionality, you're probably better off looking at one of the OAuth2 implementations available for Django Rest Framework.
This package was inspired by this Stack Overflow answer.
Expiring Tokens is tested against the latest versions of Django 1.6, 1.7 and the 1.8 preview release, and Django Rest Framework 3.1.1. It should in theory support Django 1.4.
Grab the package from PyPI.
pip install djangorestframework-expiring-authtoken
As this package uses a proxy model on the original Token model, the first step is to setup the default TokenAuthentication scheme, and check that it works.
Then, add the package to INSTALLED_APPS
along with rest_framework.authtoken
in settings.py
.
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
'rest_framework_expiring_authtoken',
...
]
Specify the desired lifespan of a token with EXPIRING_TOKEN_LIFESPAN
in
settings.py
using a
timedelta object.
If not set, the default is 30 days.
import datetime
EXPIRING_TOKEN_LIFESPAN = datetime.timedelta(days=25)
Set the authentication scheme to rest_framework_expiring_authtoken.authentication.ExpiringTokenAuthentication
on a default or per-view basis.
If you used the obtain_auth_token
view, you'll need to replace it with the obtain_expiring_auth_token
view in your URLconf.
from rest_framework_expiring_authtoken import views
urlpatterns += [
url(r'^api-token-auth/', views.obtain_expiring_auth_token)
]
If using Django 1.7 or later, you'll need to run migrate
, even though nothing
is changed, as Django requires proxy models that inherit from models in an
app with migrations to also have migrations.
python manage.py migrate
## Usage
Expiring Tokens works exactly the same as the default TokenAuth, except that using an expired token will return a response with an HTTP 400 status and a Token has expired
error message.
The obtain_expiring_auth_token
view works exactly the same as the obtain_auth_token
view, except it will replace existing tokens that have expired with a new token.
- Variable token lifespans.
- Possibly change
obtain_expiring_auth_token
to always replace an existing token. (Configurable?) - South Migrations
## Changelog
- 0.1.3
- Set a default token lifespan of 30 days.
- 0.1.2
- Changed from deprecated
request.DATA
torequest.data
- 0.1.1
- Initial release