Django rest framework Part 2: Custom Authentication

George Mutti
2 min readMar 2, 2021

In part 1 of this series, we learnt how to create a custom user model. In this part we are going to create a custom authentication. You can grab the part 1 code from this repo.

Get the code here

Authentication

Authentication is a way of validating someones identity via email, username, password, token,keys. Similar to default Django model, Django comes with default authentication as well but as it is stated in the Django documentation, you may need a custom authentication to suit your use case.

JWT Tokens

Tokens are mostly appropriate for client-side where state is stored after the user is authorized successfully. The token is stored in the local storage of the client and attached to the authorization header when making an API request which needs authentication.

Enough of talking lets get to work !!!

Installing PyJWT

Ensure you have your environment activated, then run the following command to install PyJWT, you can skip the lock by specifying — skip-lock

pipenv install PyJWT — skip-lock

PyJWT is a Python library which allows you to encode and decode JSON Web Tokens (JWT)

Updating the Models

Inside app/authentication/models.py add the following at the import section.

from datetime import datetime, timedelta
from django.conf import settings
import jwt

Under the User class add the following code.

This method generates and returns a string of the token generated

Authentication module

Inside app/authentication/serializers.py add the following code after the RegistrationSerializer class.

The above code creates a login serializer, that will be used to validate the required login credentials, and also gets the token string.

Login Endpoint(Views)

We need to receive login http request with email and password as the JSON data via our api. Write the following code in app/authentication/views.py

from .serializers import LoginSerializer

Handling Urls

We’ll update app/authentication/urls.py with the login endpoint. Add the following code.

from .views import LoginAPIViewurlpatterns = [
...
path(‘login/’, LoginAPIView.as_view(), name=’user-registration’)
]

Finally! Lets run

$ python manage.py runserverSystem check identified no issues (0 silenced).
March 01, 2021–18:21:03
Django version 3.1.7, using settings ‘app.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C

Navigate to http://127.0.0.1:8000/auth/login/ .Yeeah!! it works

--

--

George Mutti

Software developer and a problem solver. You will never be ready, do it now