Skip to content
thesarfo

Note

Authentication with Djoser

Using Djoser to get a ready-made authentication API on top of Django, choosing JWT over token-based auth, and the endpoints it provides.

views 0

Django has a full fledged authentication system, but it doesnt include an api layer. It only comes with a bunch of models and db tables you can work with. So you have to build the auth api by hand, but doing it by hand is a tedious and repetitive task. This is where a library called “Djoser” comes into place. It helps you build apis for django’s authentication system.

You can go to Djoser’s official docs to learn how to install it. But know that first you have to install it with pipenv, and then add it to the list of installed apps, and then setup a urlpattern for it in your main urls.py module.

urls.py
urlpatterns = [
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')), # after you have set up simplejwt
]

Djoser is just an api layer(a bunch of views, serializers and routes), so it actually relies on an authentication backend or authentication engine to do the work for us. So in this scenario, we have two options: either to use Token based authentication(built in drf) of Json web authentication.

TBA uses a db table to store Tokens. JWT doesnt need a database

We are going to use JWT, and to use this we have to install a library called djangorestframework_simplejwt. Now go to the docs for JWT on the Djoser docs and you will see a bunch of installation steps. ie, installing the library, adding some stuff to your settings and urls

These are the endpoints that Djoser provides for us

  • /users/
  • /users/me/
  • /users/confirm/
  • /users/resend_activation/
  • /users/set_password/
  • /users/reset_password/
  • /users/reset_password_confirm/
  • /users/set_username/
  • /users/reset_username/
  • /users/reset_username_confirm/
  • /token/login/ (Token Based Authentication)
  • /token/logout/ (Token Based Authentication)
  • /jwt/create/ (JSON Web Token Authentication)
  • /jwt/refresh/ (JSON Web Token Authentication)
  • /jwt/verify/ (JSON Web Token Authentication)