Search code examples
pythondjangorestdjango-rest-frameworkdjango-authentication

DRF - Token authentication alongside normal


I have an internal API where all ViewSets has LoginRequiredMixin because this API is used only by logged in users.

Now I need to sometimes make it available through auth_token - eg. when the user is not logged in but has a token.

I've added TokenAuthentication:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',
                                'rest_framework.filters.OrderingFilter'],

    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',


    ],
}

And tried to access API using Authorization header: Token <MYTOKEN> but it redirects all requests to log in.

How to make it work so the user has to be either authenticated or use an Authorization header?

This is a ViewSet:

class OrderViewSet(LoginRequiredMixin, ModelViewSet):
    serializer_class = OrderSerializer
    filterset_class = OrderFilter

Solution

  • On this problem, i have 2 solution for you

    1.Remove LoginRequiredMixin, because LoginRequiredMixin used for django View authentication not for django rest framework view (*authentication)

    class OrderViewSet(ModelViewSet):
        serializer_class = OrderSerializer
        filterset_class = OrderFilter
    

    and then add on setting.py file set the default permission and authentication class of REST_FRAMEWORK, like this

    REST_FRAMEWORK = {
        'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',
                                'rest_framework.filters.OrderingFilter'],
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ],
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ]
    }
    

    2.if you want to set permission and authentication add on class view, you do not have to setting.py file config. Try this

    from rest_framework.permissions import IsAuthenticated
    from rest_framework.authentication import TokenAuthentication, SessionAuthentication
    
    class OrderViewSet(ModelViewSet):
        permission_classes = (IsAuthenticated, )
        authentication_classes = (SessionAuthentication, TokenAuthentication, )
        serializer_class = OrderSerializer
        filterset_class = OrderFilter