How to implement TokenBasedAuthentication in DjangoRestFramework?

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.

Posted On 14 December 2018 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
How to Create initial django migrations for existing DB schema.

Django provides the comfort database migrations from its version 1.8, with which we can avoid the usage of third party packages like south. Adding migrations …

Continue Reading...
Django Template language Intro

We can write the required logics based on programming[python] syntax in models and views but, when we want to write simple logics we should follow …

Continue Reading...
Integration of 2checkout with django

Payment Gateways which facilitate communication within banks and Security is an integral component of all payment gateways, as sensitive data such as Credit Card Numbers …

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties