我正在使用 Django 2.0
和 Django RESET Framework
为我的应用程序编写 REST API
。
我配置了以下身份验证方法
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
到目前为止,它允许所有经过身份验证的用户访问 web api
View 。
我想要的是允许少数用户(可能是 super 管理员用户)能够通过 session 身份验证或通过登录从网络浏览器访问 API。
Edit 2: contacts/views.py
class ContactViewSet(viewsets.ModelViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
最佳答案
对于Django 2(在views.py中添加)
from rest_framework.permissions import IsAdminUser
class IsSuperUser(IsAdminUser):
def has_permission(self, request, view):
return bool(request.user and request.user.is_superuser)
class ListSmth(ListCreateAPIView):
permission_classes = (IsSuperUser,)
... Your code...
关于Django REST Framework 仅允许 super 用户访问 api Web View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50333330/