Token Authentication in DRF
Token authentication is a popular method of authentication in web APIs, where a token is generated and issued to users upon successful login, and this token is used to authenticate subsequent requests.
In this tutorial we'll learn about token authentication in Django REST Framework.
Note: In previous tutorials, we established the Students model and its corresponding serializer. Now, we will proceed by directly implementing token-based authentication.
What is Token Authentication in DRF?
-
Token-based authentication in Django Rest Framework (DRF) is a method of authenticating users in web APIs by using tokens.
-
Tokens are essentially long random strings that are generated and issued by the server upon successful user authentication.
-
These tokens serve as a means of verifying the identity of a user for subsequent API requests without requiring the client to send their username and password with every request.
Update settings.py file
Added 'rest_framework.authtoken' to our project's INSTALLED_APPS in settings.py file.
INSTALLED_APPS = [
# ...
'rest_framework',
'rest_framework.authtoken',
# ...
]
After updating the settings.py file, please apply migrations. It will create the tables required to store token-related stuff in the database.
Views.py
from rest_framework.generics import ListAPIView, CreateAPIView
from .models import Students
from .serializers import StudentsSerializer
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
class StudentsListCreateView(ListAPIView, CreateAPIView):
queryset = Students.objects.all()
serializer_class = StudentsSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
The above code defines a combined view for listing and creating student records using Django Rest Framework's ListAPIView and CreateAPIView. It utilizes token-based authentication and allows only authenticated users to access and interact with the view.
App/urls.py
from django.urls import path
from .views import StudentsListCreateView
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('students/', StudentsListCreateView.as_view(), name='students-list-create'),
path('api-token-auth/', obtain_auth_token, name='api_token_auth')
]
This code will handle token-based authentication by generating an authentication token when valid user credentials are provided via a POST request to the 'api-token-auth/' endpoint.
Now, let's check if a token gets generated or not when hitting 'api-token-auth/. We are using an extension of VSCode named "Thunder Client" to test, but you can also use other tools like Postman.
Upon sending a POST request containing user credentials such as username and password, the authentication token is successfully generated.