【发布时间】:2017-01-14 23:31:11
【问题描述】:
我正在使用 Django Rest Framework 来构建一个带有用户注册/登录的 web 应用程序。 我试图免除用户注册视图需要 CSRF 令牌。这是我现在的视图:
class UserSignUpView(generics.CreateAPIView):
permission_classes = [] # FIXME: doesn't seem to be working
serializer_class = UserSerializer
@method_decorator(csrf_exempt)
def post(self, request, *args, **kwargs):
super().post(self, request, *args, **kwargs)
def get_permissions(self):
if self.request.method == 'POST':
return (permissions.AllowAny(), TokenHasReadWriteScope())
return False
我的 settings.py 如下所示:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
我仍然在我的后端输出 Forbidden (CSRF cookie not set.): /users/ 和前端经典的 CSRF verification failed. Request aborted. 上得到这个
为什么这不起作用?这可能与我从未手动设置 CSRF cookie 的事实有关吗?
【问题讨论】:
-
get_permissions 不需要装饰器 csrf_exempt?您正在使用 POST 方法。你可以写@csrf_exempt:Documentation
-
你也可以看this post
-
@Wilfried 我尝试将
@method_decorator(csrf_exempt)添加到get_permissions的顶部,但没有变化
标签: python django django-rest-framework django-csrf