如何在Django rest框架ViewSet中对不同的功能使用不同的身份验证?
我创建了一个UserViewSet,它具有2个功能:
1.列表(列出所有已注册的用户,permission_classes应为IsAuthenticated)
2.注册(注册一个新用户,permission_classes应该是AllowAny)。
--------------------views.py-----------------------------------
class UserViewSet(ViewSet):
@list_route(methods=['get'], permission_classes = [IsAuthenticated, ])
def list(self, request):
...
...
@list_route(methods=['post'], permission_classes = [AllowAny, ])
def register(self, request):
...
...
--------------------urls.py-----------------------------------
users_list = views.UserViewSet.as_view({
'get': 'list',
'post': 'register'
})
urlpatterns = [
url(r'^$', users_list, name='users-list'),
...
...
]
--------------------settings.py---------------------------------
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
...
...
命令行注册用户:
curl -H "Content-Type: application/json" -X POST -d '{ "email":"[email protected]"}' http://192.168.30.45:8000/users/
回复:
{"detail":"Authentication credentials were not provided."}
我的“注册”功能的“ permission_class”设置为“ AllowAny”,还需要身份验证吗?为什么会这样?
您的代码似乎可以正常工作,我真的不知道出了什么问题,但是您可以尝试编写自定义权限:
class IsAuthenticatedOrCreate(permissions.IsAuthenticated):
def has_permission(self, request, view):
if request.method == 'POST':
return True
return super(IsAuthenticatedOrCreate, self).\
has_permission(request, view)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句