DEV Community

Cover image for Token authentication in Django Rest Framework
Madhuban Khatri
Madhuban Khatri

Posted on

Token authentication in 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.

settings.py

INSTALLED_APPS = [
    .
    .

    '<your_app_name>',
    'rest_framework',
    'corsheaders',

    'rest_framework.authtoken' #new
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
Enter fullscreen mode Exit fullscreen mode

views.py

from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response import Response
from django.contrib.auth.hashers import check_password

@api_view(['GET'])
def getData(request):
    users = User.objects.all()
    users_serializer = MyUserSerializer(users, many=True)
    return Response(users_serializer.data)

class TokenAuthentication(APIView):    
    def post(self, request, format=None):
        data = request.data
        if('username' in data):
            try:
                user = User.objects.get(username=data['username'])
                checkPassword = check_password(data['password'], user.password)
                if(checkPassword):
                    #If token is not created, the following will create a new token for the user instance.
                    token,created = Token.objects.get_or_create(user=user)
                    token_data = {
                        "user_id": user.id,
                        "token": token.key
                    }

                    return Response(token_data)
                else:
                    return Response("Password is incorrect.")
            except ObjectDoesNotExist:
                return Response("Invalid user details")
        else:
            return Response("Please fill the form.")
Enter fullscreen mode Exit fullscreen mode

urls.py

from django.urls import path
from . import views

urlpatterns  = [
    path('', views.getData),    
    path('token_auth/', views.TokenAuthentication.as_view())

]
Enter fullscreen mode Exit fullscreen mode

serializers.py

from rest_framework import serializers
from django.contrib.auth.models import User

class MyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
Enter fullscreen mode Exit fullscreen mode

Output

postman output img

Top comments (0)