Implement Token Authentication using Django REST Framework
Last Updated :
19 Nov, 2021
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 :
pip install django
pip install --upgrade django-crispy-forms
pip install djangorestframework
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"
Similar Reads
JWT Authentication with Django REST Framework JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement t
2 min read
Basic Authentication - Django REST Framework Authentication is a mechanism that provides access control based on the credentials associated with incoming requests. Django REST Framework provides several authentication schemes. In this section, let's look at the Basic Authentication in Django rest framework, i.e., authenticated against a user's
4 min read
How to Create a basic API using Django Rest Framework ? Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
Creating and Using Serializers - Django REST Framework In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other conten
3 min read
Using JWT for user authentication in Flask JWT (JSON Web Token) is a compact, secure, and self-contained token used for securely transmitting information between parties. It is often used for authentication and authorization in web applications. A JWT consists of three parts:Header - Contains metadata (e.g., algorithm used for signing).Paylo
6 min read
Django Authentication Project with Firebase Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of components: how to handle user authentication (signing up, signing in, signing out), a management panel for managing our website, how to uploa
7 min read