Home:ALL Converter>Django: Use both session and jwt middlewares at a time

Django: Use both session and jwt middlewares at a time

Ask Time:2018-06-21T12:16:10         Author:Santhosh

Json Formatter

I have both JWT and session authentication middleware being used.

What i found was that i was not able to login to admin. Later when i removed JWT middleware it worked.

My site will is serving as both api login and normal browser login. How to use it for both.

The only option left is the below condition for jwt.

if request.content_type == 'application/json':

How to resolve this

I am not using DRF to create api endpoints. That why i have to create custom middleware to verify JWT token

Django settings:

MIDDLEWARE = (
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'webarticles.middleware.jwtWebtoken_mod.BaseJSONWebTokenAuthentication_mod',
)

webarticles.middleware.jwtWebtoken_mod.BaseJSONWebTokenAuthentication_mod

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import exceptions
import json
from django.http import HttpResponse
from rest_framework.settings import api_settings as api_settings2
from rest_framework_jwt.settings import api_settings

jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER

class BaseJSONWebTokenAuthentication_mod(JSONWebTokenAuthentication):
    """
    Token based authentication using the JSON Web Token standard.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if request.content_type == 'application/json':
            try:
                user_auth_tuple = self.authenticate(request)
            except exceptions.APIException as e:
                self._not_authenticated(request)
                hare = e.get_full_details()
                #hare = {"e": str(e)}
                # return  HttpResponse(
                #                 json.dumps(hare),
                #                 content_type="application/json"
                #             )
                return HttpResponse(
                                json.dumps(hare),
                                content_type="application/json",
                                status=e.status_code
                            )

            if user_auth_tuple is not None:
                request._authenticator = self
                request.user, request.auth = user_auth_tuple
            else:
                self._not_authenticated(request)

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

    def _not_authenticated(self,request):
        """
        Set authenticator, user & authtoken representing an unauthenticated request.

        Defaults are None, AnonymousUser & None.
        """
        request._authenticator = None

        if api_settings2.UNAUTHENTICATED_USER:
            request.user = api_settings2.UNAUTHENTICATED_USER()
        else:
            request.user = None

        if api_settings2.UNAUTHENTICATED_TOKEN:
            request.auth = api_settings2.UNAUTHENTICATED_TOKEN()
        else:
            request.auth = None

Presently I have put the below condition to manage

if request.content_type == 'application/json':

Author:Santhosh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50960290/django-use-both-session-and-jwt-middlewares-at-a-time
yy