django-rest-framework Authentication Using basic token-based authentication


Example

Django REST Framework provides a basic token-based authentication mechanism which needs to be configured as an application in Django before being usable, so that tokens are created in the database, and their lifecycle handled.

Add Token-based authentication to settings.py

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)

Run the database migration

./manage.py migrate

Create tokens for your users

Somehow, you will have to create a token and return it:

def some_api(request):
    token = Token.objects.create(user=request.user)
    return Response({'token': token.key})

There is already an API endpoint in the token application, so that you can simply add the following to your urls.py:

urls.py

from rest_framework.authtoken import views
urlpatterns += [
    url(r'^auth-token/', views.obtain_auth_token)
]

Clients can now authenticate

Using a Authorization header like:

Authorization: Token 123456789

Prefixed by a literal "Token" and the token itself after whitespace.

The literal can be changed by subclassing TokenAuthentication and changing the keyword class variable.

If authenticated, request.auth will contain the rest_framework.authtoken.models.BasicToken instance.