Hi,
I’m building a webapp with drf which does the authentication by calling an external api. Token received from front end is sent as request parameter. Response contains the Token status (Expired or Active). My app doesn’t have a user model. So all the views should be displayed based on the status of the external api call.
To accomplish this, i have added a middleware. If the token status is expired i need to respond with 401 unauthorized. I found out drf has HttpResponseForbidden
but it is 403. which exception or response can i use here?
Is it possible to do this in drf authentication classes instead of using middleware? or is there any other way to do this?
Below is my middleware code :
from rest_framework.exceptions import AuthenticationFailed
from django.http import HttpResponseForbidden
class AuthMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
# Post call to external api
# if Token valid, do nothing
# else return Invalid token with 401 code
return HttpResponseForbidden("Invalid Token") # currently returns 403 code
except Exception as e:
print(e)
response = self.get_response(request)
return response