[英]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
的默認permission
和authentication
類,像這樣
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.如果你想在類視圖上設置permission
和authentication
添加,你不必在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.