Django-Rest User Authentication in 5 Minutes

How to add user authentication feature into your Django Rest application.

Background photo from Unsplash

Before we start, I’m strongly assuming you have
1) Basic understanding of Python
2) Basic understanding of Django and have worked a bit with Django-rest-framework
3) Already have python installed on your laptop

If the above assumptions are correct, then lets proceed.

First of all what is Authentication and why would you need it when your are building either a web or mobile application?

Authentication is a basically a gateway into your application. Normally on a lot of websites out there, you would be allowed to access some kind of informative pages about what the application e.g Pricing Page, Home Page, About Us Page, Contact Us Page etc. but when you need to access couple of other pages, you’d discover that you are asked to either login or register because at this point, they platform owners will;

1) Need a way to identify who is who on the platform
2) Create customize functionalities for users based on their submitted information
3) Store user information
4)Perform so kind of analysis with this information when necessary.

So at a point in the life-cycle of your application you will need to add “this gateway” to be able to stay informed on how and who is using your system and the growth of your application in relation to number of users. It is because of the above mentioned reasons and many more that authentication features are integrated into systems.

How do i add this authentication feature to my Django Rest application then?

Let’s begin by opening our preferred terminal and typing the following

$ mkdir djangoauthproject
$ cd djangoauthproject
$ pip3 -m venv myenv
$ source myenv/bin/activate
$ pip3 install django djangorestframework PyJWT
$ django-admin startproject DjangoUserAuth
$ cd DjangoUserAuth

This will create a folder called djangoauthproject, we then navigate into the folder and create our virtual environment and then go ahead to activate it. With our virtualenv activated, we installed django,djangorestframework, PyJWT and created our project.

You should see the following folder structure when you navigate to your project

├── manage.py
└── DjangoUserAuth
├── __init__.py
└── asgi.py
├── settings.py
├── urls.py
└── wsgi.py

Next create an app called app_account using the following command

$ python manage.py startapp app_account

At this point your project structure should be looking like this

├── manage.py
└── app_account
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
├── DjangoUserAuth
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py

Head over to the INSTALLED_APPS in your DjangoUserAuth settings.py file and register the new app you just created:

INSTALLED_APPS = (
...,
'rest_framework', #new addition
'app_account', #new addition
)

Open the urls.py file in your DjangoUserAuth folder and add the following lines of code

from django.urls import path, include #new addittion: include
...
urlpatterns = [
...,
path('api/v1/account/', include('app_account.urls')),#new addittion
]

Next add a urls.py and serializers.py in your app_account folder and your folder should be looking like this at this point

├── manage.py
└── app_account
├── __init__.py
├── models.py
├── serializers.py
├── tests.py
├── urls.py
└── views.py
├── DjangoUserAuth
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py

Inside your app_account models.py add the following code

...
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass

I normally like extending the default django User using AbstractUser in case there is need to add more things to the model in the future.

Next in your app_account serializers.py file add the following code

from rest_framework import serializers
from app_account.models import CustomUser
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class UserSerializer(serializers.ModelSerializer): class Meta:
model = CustomUser
fields = ("first_name", "last_name", "email",
"username",)
#This is used to register a user into the database
class RegisterSerializer(serializers.ModelSerializer):
first_name = serializers.CharField()
last_name = serializers.CharField()
username = serializers.CharField()
email = serializers.CharField()
password = serializers.CharField(write_only=True)
def create(self, validated_data):
return CustomUser.objects.create(**validated_data)
class Meta:
model = CustomUser
fields = ("first_name", "last_name", "email",
"username", 'password',)
#This is used to login a user
class LoginSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
user_data = UserSerializer(user).data
for key, value in user_data.items():
if key != "id":
token[key] = value
return token

for the Login, we are using pyjwt library, you can checkout more on their official doc
In your app_account views.py file add the following

from rest_framework import generic
from app_account.models import CustomUser
from app_accounts.serializers import UserSerializer, LoginSerializer, RegisterSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class LoginView(TokenObtainPairView):#user signup view
"""
User Login view
"""
serializer_class = LoginSerializer
class SignUpView(generics.CreateAPIView):#user registration view
queryset = CustomUser.objects.all()
serializer_class = RegisterSerializer

Add the following in your app_account urls.py file

from django.urls import path
from app_accounts.views import LoginView, SignUpView
urlpatterns = [
...,
path('login/', LoginView.as_view(), name="login"),
path('register/', SignUpView.as_view(), name="signup"),
]

Finally in your DjangoUserAuth settings.py file add the following

...,
AUTH_USER_MODEL = "app_account.CustomUser" #new addition
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}

We ensured django knows to use our defined custom user model and not the default user model. At this point we can go ahead and makemigrations, migrate and start our server

$ python3 manage.py makemigrations app_account
$ python3 manage.py migrate
$ python3 manage.py runserver

With our server running, if you navigate to your browser and visit
127.0.0.1:8000/api/v1/account/register/, you should see your django rest generated registration page. Go ahead a register a new user. Then navigate to 127.0.0.1:8000/api/v1/account/login/ and login in using the user credentials. A token should be generated for you on successfully login, you can copy the token and visit jwt.io and paste the encoded token and it will be decoded for you.

At this point we have successfully added an authentication feature to our django rest application.

I hope you found this article helpful. Thanks for reading.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store