JWT Authentication in Django API: A QuickStart Guide

Gokul nath
2 min readSep 18, 2023

--

Photo by Clément Hélardot on Unsplash

When you develop a Restful API using awesome Django Rest Framework, often you tend to use a default token based authentication. Although, it’s not a bad choice, the modern and secure approach is to use JWT authentication in API’s.

Ohh, wait, What is JWT authentication?!

What is JWT?

As per official documentation,

JSON Web Token (JWT) is an open standard (RFC 7519) 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. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Well, this article focus on integrating JWT authentication in Django, you can learn more about JWT here!

JWT Authentication in Django

Lets see how to implement JWT authentication in Django API step by step,

Install Simple JWT package

pip install djangorestframework-simplejwt

Add to INTSALLED APPS

INSTALLED_APPS = [
...
'rest_framework_simplejwt',
...
]

URL Configuration

from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)

urlpatterns = [
...
path('api/token/', TokenObtainPairView.as_view(), name='get_token'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='refresh_token'),
...
]

api/token/ is typically a login route whereas api/token/refresh/ is used to refresh the access token.

Default Authentication Class Configuration

REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
...
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
...
}

Enable Authentication in Class Based Views

from rest_framework import permissions

class UserViewSet(viewsets.ModelViewSet):
...
permission_classes = [permissions.IsAuthenticated]
...

Example Usage:

import requests
import json

url = "http://localhost:8000/api/token/"

payload = json.dumps({
"username": "Gokul",
"password": 123
})
headers = {
'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

# Output

{
"refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY5NDkzNzQzOCwiaWF0IjoxNjk0ODUxMDM4LCJqdGkiOiJiNDljZWJiOTQ0YmI0OTY0ODVkYWE0OWM5YTY0ZjBkNSIsInVzZXJfaWQiOjF9.4Tr3aqW5yZzsS_ikLZt8JChT0KWr_S_a9sqwr5yjW6k",
"access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjk0ODUxMDk4LCJpYXQiOjE2OTQ4NTEwMzgsImp0aSI6ImE4OTcwNzAyMjA1ZjRmYjNiYTMxYzYxMzE1YzNiZTE3IiwidXNlcl9pZCI6MX0.HumqieCcbz92Dn6WJt4Hmtg0QtNQ8az_y0JgNfW89-Q"
}

When you post correct username and password to /api/token/ endpoint, you will get two types of tokens — access token & refresh token.

access token —

By default, access token is valid for a minute but you can control this by updating ACCESS_TOKEN_LIFETIME in settings.py. Use access token in the header of subsequent requests to access other endpoints in API.

from datetime import timedelta

SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5)
}

refresh token —

By default, refresh token is valid for a day but you can control this by updating REFRESH_TOKEN_LIFETIME in settings.py.

from datetime import timedelta

SIMPLE_JWT = {
"REFRESH_TOKEN_LIFETIME": timedelta(days=5)
}

To get the access token after expiration, use refresh token to generate new access token.

import requests
import json

url = "http://localhost:8000/api/token/refresh/"

payload = json.dumps({
"refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY5NTE0ODkxNiwiaWF0IjoxNjk1MDYyNTE2LCJqdGkiOiIzZmU0ODQ5OWUzYWQ0NWMwOTlmM2U0MTE4N2Q3YmQyYyIsInVzZXJfaWQiOjF9.JomLgtwEaFHllkRI2aaieLbrLZlHSNOaRviZpAzxalU"
})
headers = {
'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

# Output

{
"access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjk1MDYyNjM4LCJpYXQiOjE2OTUwNjI1MTYsImp0aSI6IjhmZGI0MjJiYzNiMDQxMzY4NTUxNDZkMDg0ZTA2Y2JhIiwidXNlcl9pZCI6MX0.5AlSdFm_gctMu82AfkNYNpcHaEzX_16SFNFht0ZB4zg"
}

That’s all it takes to integrate JWT authentication in Django project.

Hope this helps, Thank you!!

--

--