How to create Token Based Authentication in Django Rest Framework — Part 2
In the previous story, I already start talk about token based authentication in Django Rest Framework. If you haven’t read that, you can read it first
In this story, I will show you how to create API for login. Let’s just start. Edit views.py file inside app directory
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Tokenfrom . import models
from . import serializers@csrf_exempt
@api_view(['POST'])
def login(request):
username = request.data.get("username")
password = request.data.get("password")
if username is None and password is None:
return Response({'error':'Please provide user & password'},
status=status.HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password) if not user:
return Response({'error': 'Invalid credentials'},
status=status.HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token':token.key},
status=status.HTTP_200_OK)class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ArticleSerializer
queryset = models.Article.objects.all()
permission_classes = [IsAuthenticated,]
Next, lets create url for this views
from django.urls import path, include
from rest_framework.routers import DefaultRouterfrom . import viewsrouter = DefaultRouter()
router.register(r"article", views.ArticleViewSet)urlpatterns = [
path("login/", views.login),
path("", include(router.urls)),
]
Let’s test it. We can use postman
This is what we get if we successful login
Now we are able to use this token to access the protected API as defined in the previous story
This is what we get if we access the protected API without token
Let’s use the token
This is what we will get now
Cool!!! We are success now!
This is the end of this story. Stay tune! I will cover another interesting topic.