Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Django

How to Implement TokenBasedAuthentication in DjangoRestFramework

2022-07-25

If you are new to Django REST framework, then you can go through below blog posts to understand how to develop RESTful API with Django REST framework.

How to develop RESTful webservice in Django using Django REST framework

Introduction to API development with Django REST framework

REST framework provides a number of authentication methods and also allows us to implement custom methods.

This blog shows you how to use Token Authentication to authenticate users within a Django Application. Token Authentication is a way to authorize users by using an Auth Token.

First, you have to add 'rest_framework.authtoken' to your INSTALLED_APPS setting as Token Authentication uses a special model called Token, which is used to store your user authentication tokens.

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

Then you must configure the authentication scheme to include 'TokenAuthentication' using the 'DEFAULT_AUTHENTICATION_CLASSES' setting like below

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

Now you must run 'python manage.py migrate' after adding above settings to update the database with new Token model.

You can create tokens for existing users like below

from rest_framework.authtoken.models import Token

token = Token.objects.create(user=)

This will generate a unique token for specified user & stores in Token model.

To automatically create a token whenever new user registers, add below code in post_save signal on your User model

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

REST Framework provides a built-in view that simply returns the user’s token when they provide a correct username / password.

from rest_framework.authtoken import views

urlpatterns += [
    url(r'^get-user-auth-token/', views.obtain_auth_token, name='get_user_auth_token')
]

When valid username and password fields are POSTed to the view, it will return a JSON response that looks like the following

{'token': '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'}

Token Authentication requires below header for each request, and it must be in the following format:

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

Authorization is the header key and Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b is the header value. Note that there is a space between Token and the token value.

The server will read the user’s token and finds if there is a user assigned to that particular token.

If successfully authenticated, TokenAuthentication provides the following:

'request.user' will be a Django 'User' instance.
'request.auth' will be a 'rest_framework.authtoken.models.Token' instance.