This project demonstrates how to implement JWT (JSON Web Tokens) authentication in a Django project using the rest_framework_simplejwt
library.
- Install Django and Django REST framework:
pip install django djangorestframework
- Install
rest_framework_simplejwt
:
pip install djangorestframework_simplejwt
- Add the required apps to your
INSTALLED_APPS
in your Django project's settings.py file:
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt.token_blacklist',
]
- Configure the authentication backend in your settings.py file:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
- Add the JWT URLs to your project's urls.py file:
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
...
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
- Create a Django user using the
createsuperuser
command:
python manage.py createsuperuser
- Start your Django development server:
python manage.py runserver
-
Use a tool like Postman or curl to obtain a JWT token by sending a POST request to
http://localhost:8000/api/token/
with the username and password of the created user. -
Use the obtained access token in subsequent requests to your API by including it in the Authorization header with the format
Bearer <access_token>
.