【发布时间】:2020-06-20 12:29:38
【问题描述】:
通过postman发起POST请求注册新用户返回403 Forbidden,CSRF验证失败。请求中止...通过 DRF documentation 和 knox auth documentation 我已正确设置所有内容。即使我的 DEFAULT_AUTHENTICATION_CLASSES 中没有它,Django 的 SessionAuthentication 似乎也被激活了。我已经尝试了我能找到的所有潜在解决方案,但没有任何效果。该应用程序是一个带有 React 前端的 Django rest api。任何帮助将不胜感激。
身份验证和权限设置
'DEFAULT_AUTHENTICATION_CLASSES': (
'knox.auth.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
url 调用视图 as_view
re_path('auth/register', Register.as_view(), name='register'),
基于类的注册视图扩展应处理 csrf 的 APIView
class Register(APIView):
"""User Registration API View"""
def post(self, request, *args, **kwargs):
if request.method == 'POST':
serializer = RegistrationSerializer(data=request.data)
data = {}
if serializer.is_valid():
user = serializer.save()
data['response'] = 'Account registered successfully'
data['firstName'] = user.first_name
data['lastName'] = user.last_name
data['email'] = user.email
data['token'] = AuthToken.objects.get(user=user).key
return Response(data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
堆栈跟踪错误
Forbidden (CSRF cookie not set.): /api/account/auth/register
[20/Jun/2020 12:15:14] "POST /api/account/auth/register HTTP/1.1" 403 2864
更新 我发现了这个问题并将其添加为下面的答案
【问题讨论】:
-
这能回答你的问题吗? How to disable Django's CSRF validation?
-
@ConstantinGuidon 扩展 APIView 类应该使调度方法在类 csrf_exempt 中,但是我尝试用 csrf_exempt 注释方法,但它不起作用。我尝试在类上使用 @method_decorator(csrf_exempt, name='dispatch') 也不起作用。此外,我尝试清除我的 cookie 和缓存并退出所有管理会话,但无济于事
标签: django django-rest-framework csrf django-rest-knox