简体   繁体   中英

DRF - Token authentication alongside normal

I have an internal API where all ViewSet s 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

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

You have to include 'rest_framework.authtoken' in your INSTALLED_APPS setting.


see here TokenAuthentication

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM