【问题标题】:DRF - Token authentication alongside normalDRF - 令牌认证与正常
【发布时间】:2020-04-10 21:41:42
【问题描述】:

我有一个内部 API,其中所有 ViewSets 都有 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',


    ],
}

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

如何使其工作,以便用户必须经过身份验证或使用授权标头?

这是ViewSet

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

【问题讨论】:

    标签: python django rest django-rest-framework django-authentication


    【解决方案1】:

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

    1.删除LoginRequiredMixin,因为LoginRequiredMixin用于django View 身份验证而不是django rest framework view (*authentication)

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

    然后添加setting.py文件设置默认permissionauthenticationREST_FRAMEWORK,像这样

    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.如果你想设置permissionauthentication添加类视图,你不必设置.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
    

    【讨论】:

      【解决方案2】:

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


      看这里 TokenAuthentication

      【讨论】:

      • 包含在内所以问题不在这里。
      猜你喜欢
      • 2022-11-04
      • 2017-10-29
      • 2015-12-07
      • 2017-06-29
      • 2021-08-28
      • 1970-01-01
      • 2021-05-25
      • 2020-10-07
      • 1970-01-01
      相关资源
      最近更新 更多