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.
Asked
Active
Viewed 646 times
1 Answers
1
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

Iain Shelvington
- 31,030
- 3
- 31
- 50
-
Ohk! I Will try and let you know. **Thanx** – Sumit Badsara May 23 '18 at 15:57
-
Well, using decorators is the key. Thanks, solved my problem. For other viewers, try this article too if you can't get the idea: https://medium.com/@ff73cb034b5a/54fddb2a1679 – Sumit Badsara Jun 17 '18 at 16:49