Django Rest Framework (DRF) is a powerful toolkit for building Web APIs in Django. JWT (JSON Web Tokens) is a popular authentication method for securing RESTful APIs. Here, I’ll provide you with an example of how to implement JWT authentication in a Django Rest Framework project.
First, make sure you have Django and Django Rest Framework installed. You can install them using pip if you haven’t already:
pip install django djangorestframework djangorestframework-jwt
Next, create a new Django project or use an existing one. For this example, we’ll create a new project and a sample app.
- Create a new Django project and a sample app:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
- Configure Django settings for the app:
In your project’s settings.py
, add 'rest_framework'
and 'myapp'
to the INSTALLED_APPS
:
INSTALLED_APPS = [
# ...
'rest_framework',
'myapp',
# ...
]
- Configure Django Rest Framework settings:
In the same settings.py
file, add the following configurations:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
JWT_AUTH = {
'JWT_SECRET_KEY': 'your-secret-key', # Change this to your own secret key.
'JWT_ALGORITHM': 'HS256',
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7),
}
Replace 'your-secret-key'
with a strong, secret key for your application.
- Create a user model:
In your myapp/models.py
, define a custom user model or use Django’s built-in User
model:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
# Add any additional fields you need
pass
- Create serializers and views:
Create serializers for your data and views for your API endpoints in your myapp
app.
- Configure URLs:
In your myapp/urls.py
, configure the URLs for your views:
from django.urls import path
from myapp import views
urlpatterns = [
path('api/token/', views.CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', views.CustomTokenRefreshView.as_view(), name='token_refresh'),
# Add your other API endpoints here
]
- Create JWT views:
In your myapp/views.py
, create custom JWT views using Django Rest Framework’s TokenObtainPairView
and TokenRefreshView
:
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .serializers import CustomTokenObtainPairSerializer
class CustomTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
class CustomTokenRefreshView(TokenRefreshView):
pass
- Create a serializer for the token:
In your myapp/serializers.py
, create a custom serializer for the token:
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
# Add any additional fields you need here
pass
- Migrate the database:
Run the following commands to create the necessary database tables:
python manage.py makemigrations
python manage.py migrate
- Create a superuser:
Create a superuser to access the Django admin site and test your API:
python manage.py createsuperuser
- Test your API:
Start the development server:
python manage.py runserver
You can now test your API using tools like curl
, httpie
, or a frontend client.
To obtain a JWT token, make a POST request to the /api/token/
endpoint with your superuser’s credentials. Then, you can use the token for authentication in your API requests.
Remember to handle token expiration and refresh as needed in your frontend or client application.