Adding Data to Request in Django REST Framework in Authentication Class

607 Views Asked by At

Suppose I have the following Authentication class in DRF. If the request is authenticated, then I need some additional data in the request object. Say, REQUIRED_DATA is that variable.

class MyAuthClass(BaseAuthentication):
    
    def authenticate(self, request):
        # suppose is_authenticated_request and authenticated_user are methods
        # which return the responses as described by their name
        if is_authenticated_request(request):
            user = authenticated_user(request)
            request.REQUIRED_DATA = some_variable_of_any_type
            return (user, None)
        raise exception.AuthenticationFailed(_('Authentication failed.'))

Here is how I used it in the viewset.

class MyViewSet(viewsets.GenericViewSet):
    authentication_classes = [MyAuthClass]
    permission_classes = [permissions.IsAuthenticated]

    def create(self, request, *args, **kwargs):
        #############
        # ......... #
        request.REQUIRED_DATA # using variable
        # ......... #
        #############

Am I going right?

I need this variable after the request is authenticated. Is their a better way to do this? Middleware is one but Middleware runs for each request, I need for this viewset only.

0

There are 0 best solutions below