Django Rest API using Django REST Framework- Authentication

Authentication is one of the major parts of any application either it is web or desktop. In this tutorial, we are going to learn Authentication using Django REST Framework. We can authenticate in two way:
1. Using Django REST Framework’s built-in authentication
2. Using Rest-auth module

Let’s start with the built-in authentication process. In this process, first of all, we need to add rest_framework support and define authentication classes. Open the settings.py file and navigate to the bottom of the file and write down the following code:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

Here we need to add some authentication classes. by default Django uses SessionAuthentication.

We created view class and URL for other API endpoints in previous time but for authentication, we don’t need to create any view or serializer classes. Because the Django rest framework already created all these staffs. We only need to include the Django rest framework’s URL. So open urls.py in codekit  and follow the code snippet below:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/', include('rest_framework.urls')),
    path('api/', include('codekitapp.urls'))
]

Here auth will be set to the Django rest framework login and logout view. Just hit http://127.0.0.1:8000/auth/login and you will see like below image:


About Author

Nasir

Welcome to CodeKit.xyz. I am working in an automation company as a software engineer. From the deep thirst of learning, I have developed this platform.