簡體   English   中英

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',


    ],
}

並嘗試使用 Authorization header: Token <MYTOKEN>訪問 API,但它重定向了所有登錄請求。

如何使其工作,以便用戶必須經過身份驗證或使用 Authorization 標頭?

這是一個ViewSet

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

關於這個問題,我有 2 個解決方案

1.移除LoginRequiredMixin ,因為LoginRequiredMixin用於 django View 認證而不是 django rest 框架視圖 (*authentication)

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

然后在setting.py文件中添加REST_FRAMEWORK的默認permissionauthentication類,像這樣

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添加,你不必在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

您必須在 INSTALLED_APPS 設置中包含“rest_framework.authtoken”。


看這里TokenAuthentication

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM