Ask Your Question
3

What is the process to incorporate authentication and authorization using JSON Web Tokens (JWT) into a Django REST API?

asked 2023-02-18 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2022-03-01 03:00:00 +0000

scrum gravatar image

Here are the steps to incorporate authentication and authorization using JSON Web Tokens (JWT) into a Django REST API:

  1. 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
    
  2. 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
    }
    
  3. 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,
    }
    
  4. 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
    
  5. 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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-02-18 11:00:00 +0000

Seen: 11 times

Last updated: Mar 01 '22