Here are the steps to incorporate authentication and authorization using JSON Web Tokens (JWT) into a Django REST API:
Install necessary dependencies: You’ll need to install the PyJWT and django-rest-framework-jwt packages. Use pip to install these packages in your virtual environment.
pip install PyJWT django-rest-framework-jwt
Add JWT authentication to the DRF authentication settings: In your Django settings.py file, add 'rest_framework_jwt.authentication.JSONWebTokenAuthentication'
to the REST_FRAMEWORK
DEFAULT_AUTHENTICATION_CLASSES
list.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
# other authentication classes
),
# other settings
}
Configure JWT settings: Next, add the JWT settings to your Django settings file.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
# other authentication classes
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
# other permission classes
),
# other settings
}
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
}
Create a custom JWT response handler: You can create a custom response handler to return additional information in the response, such as user details or permissions.
# utils.py
from rest_framework_jwt.utils import jwt_response_payload_handler as drf_jwt_response_handler
def jwt_response_payload_handler(token, user=None, request=None):
"""
Returns additional user data along with the JWT token
"""
response_data = drf_jwt_response_handler(token, user, request)
response_data.update({
'user_id': user.id,
'username': user.username,
})
return response_data
Apply authentication and permission classes to views: Finally, apply the authentication_classes
and permission_classes
decorators to your views.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class ProtectedView(APIView):
authentication_classes = (JSONWebTokenAuthentication,)
permission_classes = (IsAuthenticated,)
def get(self, request):
"""
Returns the current user details
"""
user = request.user
return Response({'user_id': user.id, 'username': user.username})
That’s it! You now have a Django REST API that is secured with JWT authentication and authorization.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-02-18 11:00:00 +0000
Seen: 11 times
Last updated: Mar 01 '22
What is OCPP Authorization and can you explain it in different words?
How can the oauth flow in httr2 be modified to utilize id_token instead of access_token?
What are the steps to enable Keycloak to receive POST requests at an authorization endpoint?
Can you restate the following question: How do Web API, OWIN, and SignalR relate to Authorization?
How can I resolve the HttpClient authorization issue when using a Bearer Token?