JWT Authentication — Django Rest Framework

Build a Product Review Backend with DRF — Part 7

Emre Cevik
Python | Django & Rest
5 min readOct 18, 2020

--

What is JWT?

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWT used to create access tokens for an application. JWT is good for API authentication, and server-to-server authorization.

The server generates a token that certifies the user identity, and sends it to the client. The client will send the token back to the server for every subsequent request, so the server knows the request comes from a particular identity.

https://flaviocopes.com/jwt/

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are header, payload and signature.

Header : Identifies which algorithm is used to generate the signature.
Payload : Contains a set of claims. Claims are statements about an entity. Signature : Securely validates the token.

We’ll use django-rest-framework-simplejwt package for JWT authentication.

Simple JWT provides a JSON Web Token authentication backend for the Django REST Framework. It aims to cover the most common use cases of JWTs by offering a conservative set of default features. It also aims to be easily extensible in case a desired feature is not present.

First we need to install django-rest-framework-simplejwt package

pip install djangorestframework-simplejwt

After installation completes, we must explicitly tell DRF which authentication backend we want to use. Open up medium/settings.py and create new key in REST_FRAMEWORK:

In your medium/urls.py file, include routes for Simple JWT’s TokenObtainPairView and TokenRefreshView views:

We need to create protected views for testing. Open reviews/views.py and type the following lines of code:

The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in DRF. We set IsAuthenticated permission to ImageViewSet. We’ll learn information about permission in the next parts.

If you attempt to request a resource without the authentication header, you will get the following error.

For obtaining a token we should send a POST request to API. Request body must have two parts : username and password.

If the login attempt is successful, the response will look like this:

To access the protected views, you should include the access token in the header of all requests, like this:

After five minutes the token will be expire. If you try to access the protected views, you are going to get the following error:

To get a new access token, you should use the refresh token :

To access the protected views, you should replace the token in the header:

Default Simple JWT Settings :

Only with a valid Access token can the user access a protected view, otherwise DRF will return a 401 unauthorized error. Access token expires in 5 minutes. We need to refresh token if access token expires. The refresh token is valid for 24 hours. When it expires, the user will need to perform a full authentication again. We can change refresh token lifetime to 15 days. And we can rotate the refresh tokens so that our users don’t have to log in again if they visit within 15 days.

For these settings open up medium/settings.py and type the following lines of code:

Add custom claims to payload :

Default payload includes the user_id. You can add any information you want, you just have to modify the claim.

For add claims to payload we need to create a subclass for TokenObtainPairView as well as a subclass for TokenObtainPairSerializer.

Open reviews/serializers.py and type the following lines of code:

Open reviews/views.py and type the following lines of code:

Open medium/urls.py and type the following lines of code:

To see the new token send POST request api and obtain new token:

There you can see username in the decoded token payload:

Detailed descriptions for django-rest-framework-simplejwt you can check

You can download part 7 files from

If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out parts of this series!

--

--