Using djoser in Django for token authentication without views

PythonServer Side ProgrammingProgramming

Djoser is a simple authentication library for Django. It is used to generate tokens for authentication; this generated token is generated by taking three fields: username, email and password. It only works on POST request, but you can add its frontend.

Example

Create a Django project and an app. I named them "DjoserExample" and "myapp".

Install two packages −

pip install djoser
pip install djangorestframework

In settings.py, add the following lines −

INSTALLED_APPS = [
#below every other apps
   'myapp',
   'rest_framework',
   'rest_framework.authtoken',
   'djoser'
]

# Below template variable
REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
      'rest_framework.authentication.TokenAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': [
      'rest_framework.permissions.IsAuthenticated',
   ]
}
DJOSER = {
   "USER_ID_FIELD": "username"
}

Here we added djoser and restframework as an app. Then we added authentication backend of REST framework and for djoser, we added the User ID field (i.e., the Index field).

We are using default User Authentication database of Django, so we actually don't need an app.

Go to project's urls.py and add the following lines −

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

urlpatterns = [
   path('admin/', admin.site.urls),
   path('',include('myapp.urls')),
   path(r'api/v1/', include('djoser.urls')),
   path(r'api/v1/token/login, include('djoser.urls.authtoken'))
]

Here we defined djoser admin url and then djoser authentication backend.

With that, everything is set. Now run these commands on the terminal and check the output −

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Output

On http://127.0.0.1:8000/api/v1/users/ −

Here you will create the user.

On http://127.0.0.1:8000/api/v1/token/login −

Here you will generate token for the user by providing username and password.

raja
Published on 26-Aug-2021 13:25:40
Advertisements