【发布时间】:2017-01-06 04:38:03
【问题描述】:
如何在一个Django Rest框架ViewSet中对不同的功能使用不同的认证?
我创建了一个 UserViewSet,它有 2 个功能:
1. list(列出所有注册的用户,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":"user@example.com"}' http://192.168.30.45:8000/users/
回复:
{"detail":"Authentication credentials were not provided."}
我的“注册”功能的“permission_class”设置为“AllowAny”,还需要认证吗?为什么会这样?
【问题讨论】:
标签: django django-rest-framework