如何在Django休息框架ViewSet中对不同的函数使用不同的身份验证?
我创建了一个UserViewSet,它有两个函数:
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”,还需要身份验证吗?为什么会这样?
答案 0 :(得分:2)
您的代码似乎有效,我不知道问题是什么,但您可以尝试编写自定义权限:
class IsAuthenticatedOrCreate(permissions.IsAuthenticated):
def has_permission(self, request, view):
if request.method == 'POST':
return True
return super(IsAuthenticatedOrCreate, self).\
has_permission(request, view)