Django REST Framework仅允许超级用户访问api Web视图 [英] Django REST Framework allow only superusers to access api web view
问题描述
我正在使用 Django 2.0
和 Django RESET Framework
编写 REST API
用于我的应用程序。
I'm using Django 2.0
and Django RESET Framework
to write REST API
for my application.
我已经配置了以下身份验证方法
I have configured following authentication methods
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
到目前为止,它允许所有经过身份验证的用户可以访问 Web api
视图。
As of now, It allows all authenticated users to access web api
view.
我想要的是允许几个用户(可能是超级管理员)用户)可以通过登录从会话身份验证或Web浏览器访问API。
编辑2:联系人/ views.py
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)
推荐答案
因此您可以利用 permission_classes
来执行此操作。 DRF的 Request
对象记住在名为 _authenticator
的属性中使用的身份验证方法。您可以使用它;并使用permission_classes来确定(用户,验证者)对是否具有权限
So you can leverage permission_classes
to do this. DRF's Request
object remembers the authentication method that was used in an attribute called _authenticator
. You can use this; and use the permission_classes to determine if the pair of (user, authenticator) has permission
class AdminAuthenticationPermission(permissions.BasePermission):
ADMIN_ONLY_AUTH_CLASSES = [rest_framework.authentication.BasicAuthentication, rest_framework.authentication.SessionAuthentication]
def has_permission(self, request, view):
user = request.user
if user and user.is_authenticated():
return user.is_superuser or \
not any(isinstance(request._authenticator, x) for x in self.ADMIN_ONLY_AUTH_CLASSES)
return False
class ContactViewSet(viewsets.ModelViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
permission_classes = (IsAuthenticated, AdminAuthenticationPermission,)
未经测试:但可以使用
这篇关于Django REST Framework仅允许超级用户访问api Web视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!