Django REST Framework JWT Authentication



If you ever worked with Django REST framework, then you surely know about JWT authentication. JWT authentication is used for token authentication and it is really a popular method for authentication in Django. JWT stand for JSON Web Token. Let's see how to work with it.

First, install a package −

pip install djangorestframework-simplejwt
pip install djangorestframework

We are not going to need an App for this, we will just do a basic setup for Django REST framework frontend and authentication backend.

Example

In settings.py, add the following −

INSTALLED_APPS = [
...
'rest_framework_simplejwt',
'rest_framework'
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
   )
}

Here, we added the rest_framework and JWT auth framework as an app and for authentication backend, we added JWT auth.

In project's urls.py

from django.urls import path
from rest_framework_simplejwt.views import (
   TokenObtainPairView,
   TokenRefreshView,
)
urlpatterns = [
   path('admin/', admin.site.urls),
   path('api/token/', TokenObtainPairView.as_view(), name='t
oken_obtain_pair'),
   path('api/token/refresh/', TokenRefreshView.as_view(), na
me='token_refresh'),
]

Here, we added two extra urls, one is for generating token in with username and password and the other is for authentication using generated token.

Output


Updated on: 2021-08-25T13:11:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements