Search code examples
djangomiddlewaredjango-middleware

Custom Middleware in Django with Exclusions


I require to check authentication via token during execution of certain views, while some views can be accessed without authentication. So, how do i make a middleware and exclude some views from it. Any other idea to solve this is appreciated.


Solution

  • I would suggest taking inspiration from the csrf middleware that Django provides

    from django.utils.deprecation import MiddlewareMixin
    
    class MyAuthenticationMiddleware(MiddlewareMixin):
    
        def process_view(self, request, callback, callback_args, callback_kwargs):
    
            if getattr(callback, 'my_exempt_flag', False):
                return None
    
            # Authentication goes here
            # Return None if authentication was successful
            # Return a HttpResponse with some error status if not successful
    

    And create a decorator to wrap your views

    from functools import wraps
    
    def exempt_from_my_authentication_middleware(view_func):
        def wrapped_view(*args, **kwargs):
            return view_func(*args, **kwargs)
        wrapped_view.my_exempt_flag = True
        return wraps(view_func)(wrapped_view)
    

    Can be used like so

    @exempt_from_my_authentication_middleware
    def my_view(request):
        # TODO