How to authenticate using external endpoint

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

@KenWhitesell Could you please provide any suggestion here ?

Sorry, I’m not going to be much help here - I’ve got no direct experience with what you’re trying to do. (Specifically, we do very little with DRF.)

The closest parallel that I’ve worked with is that we have a couple of Django projects using CAS as the external authentication source. Even though the authentication (and therefore the users) are external to the projects, we still keep “shadow User” objects in Django to handle authorization requirements.

I was able to solve it by decorating the view class and methods with the below function

def auth(func):

    def wrapper(request,*args,**kwargs):

        # Post call to external api

        # if Token valid, do nothing

        # else return Invalid token with 401 code

        return JsonResponse({"response": "Token Invalid"}, status=status.HTTP_401_UNAUTHORIZED)

        return func(request,*args,**kwargs)

    return wrapper