Wednesday, December 25, 2024
Google search engine
HomeLanguagesImplement Token Authentication using Django REST Framework

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 

Python3




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/viewsets.py 

Python3




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


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

Python3




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


Editing url.py
goto to project/urls.py
and edit it 
Import router and rest_framework.authtoken for token authentication 

Python3




from .router import router
from rest_framework.authtoken import views


add API related paths
 

Python3




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


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"

RELATED ARTICLES

Most Popular

Recent Comments