Customizing URLs in Djoser

INTRODUCTION

Authenticating or verifying users is essential while building secure apps to prevent unauthorized access, and also, to keep an individual’s information safe. In Django, authentication can be done with the in-built libraries and classes, or third-party libraries. For the purpose of this article, the Djoser library will be used.

Djoser is an open-source authentication library for Django. It is a simple library for providing basic authentication in a Django app, and it is used alongside the Django REST Framework. In this article, we will be looking at how to customize URLs in Djoser.

Prerequisite: Python.

Let's dive in!

1. Setting up the environment

The first thing to do is to set up a virtual environment where the following libraries would be installed: Django, Django REST Framework, and Djoser. The pipenv library would be used (if you do not have the pipenv library, you can install it here). Navigate to the desired location for the creation of the project and run the command

C:\Users\Demo> pipenv shell

This command would create a virtual environment and launch it immediately. This would also create a Pipfile and have something like this inside

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

[requires]
python_version = "3.9"

2. Installing libraries

After setting up the environment, the libraries can be installed

C:\Users\Demo> pipenv install django==3.2
C:\Users\Demo> pipenv install djangorestframework
C:\Users\Demo> pipenv install djoser
C:\Users\Demo> pipenv install djangorestframework_simplejwt

3. Creating and configuring a Django project

The next step is to create a Django project.

C:\Users\Demo> django-admin startproject demo .

Then create an app.

C:\Users\Demo> django-admin startapp authenticate

Open up the settings.py file on your code editor and add the following to the INSTALLED_APPS,

INSTALLED_APPS = [
    'rest_framework',
     'djoser',

     ‘authenticate’,
]

In this tutorial, the JWT authentication will be used. Add rest_framework.authentication.JWTAuthentication to Django REST Framework authentication strategies tuple

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

Configure the django-rest-framework-simplejwt to use the Authorization: JWT <access_token> header

SIMPLE_JWT = {
   'AUTH_HEADER_TYPES': ('JWT',),
}

Finally, run migrations.

python manage.py migrate

The Djoser library comes with various settings depending on the context of what has to be done with the library. The full settings can be found on the documentation.

Now, the app is halfway set up. Djoser comes with the following endpoints already needed for authentication. These endpoints come with the URLs beginning with /users/. This is kind of funny, right? This is where customization comes into play.

4. Customizing the URLs

Configuring the URLs in the base URL file,

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("authenticate.urls")),
]

Create a urls.py file for the URL endpoints in the authenticate app and import the following

from django.urls import path

Some of the default endpoints in Djoser look like this

/users/
/users/resend_activation/
/users/activation/
/users/set_password/
/users/reset_password/
/users/reset_password_confirm/
/jwt/create/ (JSON Web Token Authentication)

To customize, the UserViewSet class is used. The UserViewSet is a class that contains all the URLs listed in the list of endpoints and their permissions. These endpoints can be called directly into the as_view() function to use. The as_view() function takes in the type of request and the endpoint’s name as a dictionary. This can also be done to other endpoints that must be customized to your taste.

On customization, the URL becomes

from djoser.views import UserViewSet
from rest_framework_simplejwt.views import TokenObtainPairView

app_name = "authenticate"


urlpatterns = [
    path('register/', UserViewSet.as_view({'post': 'create'}), name="register"),
    path("login/", TokenObtainPairView.as_view(), name="login"),
    path("resend-activation/", UserViewSet.as_view({"post": "resend_activation"}), name="resend_activation"),
    path("activation/<str:uid>/<str:token>/", UserViewSet.as_view({"post": "activate"}), name="activate"),
    path("reset-password/", UserViewSet.as_view({"post": "reset_password"}), name="reset_password"),
    path("reset-password-confirm/<str:uid>/<str:token>/", UserViewSet.as_view({"post": "reset_password_confirm"}), name="reset_password_confirm"),
]

CONCLUSION

With Djoser, developers can focus on writing the actual logic of their software without worrying much about authentication. Djoser provides a secure and relatively easy-to-customize system on which all authentication in a project can be built on. The code used in the example can be found here.

Feel free to reach me on Twitter if you encounter any problems.

Thank you!