DRF - 令牌认证与正常

DRF - Token authentication alongside normal

我有一个内部 API,其中所有 ViewSet 都有 LoginRequiredMixin,因为这个 API 仅供登录用户使用。

现在我有时需要通过 auth_token 使其可用 - 例如。当用户未登录但有令牌时。

我添加了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',


    ],
}

并尝试使用授权 header 访问 API:Token <MYTOKEN> 但它会重定向所有登录请求。

如何让它工作,以便用户必须经过身份验证或使用授权 header?

这是一个ViewSet:

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

您必须在 INSTALLED_APPS 设置中包含 'rest_framework.authtoken'。


看这里 TokenAuthentication

关于这个问题,我有2个解决方案给你

1.Remove LoginRequiredMixin, 因为 LoginRequiredMixin 用于 django View 认证而不是用于 django rest framework view (*authentication)

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

然后在 setting.py 文件上添加 REST_FRAMEWORK 的默认 permissionauthentication class,像这样

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 你想设置 permissionauthentication 添加到 class 视图,你不必 setting.py 文件配置。试试这个

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