Open In App
Related Articles

Implement Token Authentication using Django REST Framework

Improve Article
Save Article
Like Article

Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works by providing token in exchange for exchanging usernames and passwords.

Modules required :

  • django : 
pip install django
  • crispy_forms : 
 pip install --upgrade django-crispy-forms 
  • django rest_framework : 
pip install djangorestframework
  • HTTPie : 
pip install httpie

and a project to add API, here we are using Sign Up and log in

Creating Viewset and Serializers

Go to user folder in given project 
and make a api folder to keep all api related files  

 cd user && mkdir api 

Now, make user/api/ and user/api/ in api folder

 cd user/api && touch 

now edit user/api/ 


from rest_framework import serializers
from django.contrib.auth.models import User
class userSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields =  '__all__'

also edit user/api/ 


from rest_framework import viewsets
from .serializers import userSerializers
from django.contrib.auth.models import User
class userviewsets(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = userSerializers

add rest_framework and rest_framework.authtoken in INSTALLED_APPS in

Edit rest_framework settings as below 



Creating router 
goto project/ and create 

 cd project/ && touch 

edit project/


from user.api.viewsets import userviewsets
from rest_framework import routers
router = routers.DefaultRouter()
router.register('user', userviewsets, base_name ='user_api')

goto to project/
and edit it 
Import router and rest_framework.authtoken for token authentication 


from .router import router
from rest_framework.authtoken import views

add API related paths


path('api/', include(router.urls)),
path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),

Testing API 
first, migrate models  

python migrate 

start server using below command  

python runserver

open another terminal and let us check our API using HTTP POST request for a token and paste username and password. 

http POST http://localhost:8081/api-token-auth/ username='your_username' password="your_password"

now use this token to get data from API, place your API token 

http http://localhost:8081/api/user/ "Authorization: Token API_KEY_HERE"

Last Updated : 19 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials