Step 1: Install Necessary Packages
First, you need to install the required packages. For JWT authentication in Django, you can use the djangorestframework-simplejwt
package.
pip install djangorestframework djangorestframework-simplejwt
Step 2: Configure Django Settings
Add rest_framework
and rest_framework_simplejwt
to your INSTALLED_APPS
in settings.py
.
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt',
...
]
Next, configure the REST framework to use JWT for authentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
Step 3: Set Up URLs
In your urls.py
, include the views for obtaining and refreshing tokens.
from django.urls import path
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'),
...
]
Step 4: Create Views and Protect Endpoints
Create views and protect your endpoints using the @api_view
decorator and the permission_classes
attribute.
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected_view(request):
return Response({'message': 'This is a protected view'})
Step 5: Testing
To test your JWT implementation, you can use tools like Postman or CURL to interact with your API. First, obtain a token by making a POST request to /api/token/
with your username and password.
curl -X POST http://localhost:8000/api/token/ -d "username=yourusername&password=yourpassword"
This will return a response containing the access and refresh tokens. Use the access token to access protected endpoints by including it in the Authorization header.
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/protected-endpoint/
Example Project Structure
Here is a basic project structure for reference:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
__init__.py
views.py
models.py
urls.py
Example settings.py
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_simplejwt',
'myapp',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
# Additional settings...
Example urls.py
# urls.py
from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from myapp.views import protected_view
urlpatterns = [
path('admin/', admin.site.urls),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('protected/', protected_view, name='protected_view'),
]
How It Works
The TokenObtainPairView
and TokenRefreshView
views provided by djangorestframework-simplejwt
are already implemented and ready to use. You do not need to create additional views for these endpoints. They are automatically generated when you include them in your urls.py
.
- TokenObtainPairView: This view is used to obtain a pair of access and refresh tokens. You POST to this endpoint with user credentials (username and password) to get the tokens.
- TokenRefreshView: This view is used to refresh the access token. You POST to this endpoint with a valid refresh token to get a new access token.
Example Requests
- Obtain Token Pair:
curl -X POST http://127.0.0.1:8000/api/token/ -d "username=myusername&password=mypassword"
This will return a JSON response with access
and refresh
tokens.
- Refresh Token:
curl -X POST http://127.0.0.1:8000/api/token/refresh/ -d "refresh=your_refresh_token"
This will return a new access
token.
Example Response
- TokenObtainPairView Response:
{
"refresh": "your_refresh_token",
"access": "your_access_token"
}
- TokenRefreshView Response:
{
"access": "your_new_access_token"
}
With these steps, you can seamlessly integrate JWT authentication into your Django application using djangorestframework-simplejwt
. There is no need to create additional views for these token endpoints as they are provided out of the box by the package.