Authenticate Django APIs with JWT!

Sandeep Chauhan
2 min readFeb 27, 2020

Hello there! In this article, we are going to understand the use of JWT(JSON Web Token)for the authentication of the APIs in the Django app. So, I am skipping the beginning part of creating a Django project(say project) and the Django app(say app). We’ll use the “rest framework” to create API.

pip install djangorestframework

To generate JWT tokens, we’ll use “simplejwt” library.

pip install djangorestframework-simplejwt

Now, do some basic settings related to rest-framework and simplejwt. Add rest_framework in the “INSTALLED APPS” in project/settings.py

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
AUTH_USER_MODEL = "app.UserModelName"

Put the above code in settings.py, we are setting the default authentication class to “rest_framework_simplejwt.authentication.JWTAuthentication” and the replace “app.UserModelName” with your app’s user model.

Now everything is set, we have to move to the API and its Authentication part. There are two ways, one is to use the standard built-in API of simplejwt, and another is to use the functions that can help in customizing the generation of tokens.

Use of standard API:

path('access-token/', TokenObtainPairView.as_view()),
path('access-token/refresh/', TokenRefreshView.as_view()),

put the above code in `urlpatterns` of project/urls.py. When you will hit access-token/ , you’ll get two types of tokens “access and refresh”. The access token is used for authentication which can be used as “Authorization Bearer” and refresh will be used to generate access token again by using the access-token/refresh/ endpoint. An access token has less lifetime in comparison to refresh. You can also change its properties by adding the below code in settings.py.

SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
...
}

Now, In the second method, our main purpose is to get tokens generated by the user id. For this, we’ll use RefreshToken and pass the user in it.

def get_token(user):
token = RefreshToken.for_user(user)
return {
'access-token': str(token.access_token),
'refresh-token': str(token),
}

Here we have defined a function to generate the tokens which is taking the user as an argument and pass it to RefreshToken.for_user() and returning the access-token and refresh-token.

Now, we have tokens, we have to only authenticate the user with the help of these tokens. You can add permission_classes=(IsAuthenticated,) to your API view. It’ll verify the token on its own and authenticate the user.

RefreshToken() can also be used to get access token by the refresh token, pass refresh token like RefreshToken(refresh_token) and will get both refresh and access token.

If you have any need to decode it and get its details like user_id, expiry, and etc. So, you can do it like this

import jwt
...
decodedPayload = jwt.decode(token, None, None)
user_id = decodePayload['user_id']
token_type = decodePayload['token_type']
expiry = decodePayload['exp']
...

you can get user id, token type, expiry and other things from the decoded payload.

For more details, take a look at code and its documentation here. Hopefully, you have an idea to use JWT with Django APIs.

Thanks for the read. Best of luck. Suggestions would be appreciated. Follow me on twitter for updates about upcoming posts.

--

--