Search code examples
djangorestauthenticationdjango-rest-frameworkapi-design

Conditionally authenticate users to DRF view


I have a DRF view as such:

class DocumentsView(generics.ListCreateAPIView):
    permission_classes = ()
    authentication_classes = ()
    # I typically enforce authentication with 
    # authentication_classes = (JWTCookieAuthentication,)

    def list(self, request):
        pagination_class = None
        
        if request.user.is_authenticated: 
           ... return protected data ...
        else:
           ... return generic data ...

I want to allow both users sending a valid token and those not sending a valid token to both get a response from this endpoint. However, request.user.is_authenticated returns False, even when a valid token is sent (I understand why). How can I try to authenticate the user, but still allow them to proceed even if not presenting a token?

Or is better practice to not have the same view to authenticated an unauthenticated users?


Solution

  • What you want is to have no permissions, but still perform authentication.

    Authentication validates tokens, gets the user from the database, etc. If you disable it, then no checks of tokens/etc will be performed. This means request.user will always equal AnonymousUser.

    class MyView(ListCreateApiView):
        permissions_classes = [AllowAny]
        
    

    It's worth considering using AllowAny as your permission. It is the same as using a blank list [], but makes it clear your intention is to make the view public, rather than a mistake.