Implement Token Authentication using Django REST Framework

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/serializers.py and user/api/viewsets.py in api folder

 cd user/api && touch serializers.py viewsets.py 



now edit user/api/serializers.py

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


also edit user/api/viewsets.py

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Edit settings.py

add rest_framework and rest_framework.authtoken in INSTALLED_APPS in setting.py

Edit rest_framework settings as below


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

}

Creating router
goto project/ and create router.py



 cd project/ && touch router.py 

edit project/router.py,

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Editing url.py

goto to project/urls.py

and edit it
Import router and rest_framework.authtoken for token authentication

filter_none

edit
close

play_arrow

link
brightness_4
code

from .router import router
from rest_framework.authtoken import views

chevron_right


add API related paths

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Testing API
first, migrate models

python manage.py migrate 

start server using below command

python manage.py 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"

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

A Computer Science and Engineering undergraduate student at IERT, Allahabad with an interest in Programming, Data Science/AI and web development

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.