我正在尝试使用Django Rest Framework进行简单的登录页面,并且我一直收到csrf令牌错误。为了解决这个问题,我已经在我的登录方法上添加了@csrf_exempt注释,但它是不安全的。
这是我的方法:
@csrf_exempt
def login(request):
print(request.COOKIES)
username = request.POST.get('username')
password = request.POST.get('password')
print("username {} password {}".format(username, password))
user = authenticate(request, username=username, password=password)
group = None
if user is not None:
django_login(request, user)
request.session.set_expiry(0)
result = True
status = 200
else:
result = False
status = 401
data = {'result': result, 'username': username}
return HttpResponse(json.dumps(data), content_type="application/json", status=status)
My Rest Framework设置:
REST_FRAMEWORK = {
'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S",
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.SearchFilter',
'django_filters.rest_framework.DjangoFilterBackend',
),
'EXCEPTION_HANDLER': 'common.custom_exception_handler.custom_exception_handler'
}
没有csrf_exempt
注释,我得到了
Forbidden (CSRF token missing or incorrect.): /authentication/login
然而,当我打印cookies 时,我实际上在我的cookie中获得了一个令牌。
我重新添加@csrf_exempt注释时会打印 {'csrftoken': 'HZc8vPqoad...7eIvTzep', 'sessionid': 'n71c....g5c7'}
。
在我的角度代码中,我还尝试将csrf标记附加为带有'X-CSRFToken'的请求标头,但我发现了两件事
1)在我的请求中,我从document.cookies
获得的X-CSRFToken与上面的标记不同。有两种不同的CSRF令牌 - 为什么?
如果您注意到,X-CSRFToken标头和Cookie中的标记有所不同。我收到了相同的CSRF token missing or incorrect.
2)即使我删除了使用JWT身份验证,它也没有效果。
我还尝试在我的app.module中使用新的Cookie策略替换新的XSRF策略,如下所示:
{
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
}
但无济于事 - 我得到了第(1)点中描述的相同问题。
但是,当我重新添加@csrf_exempt
注释并检查请求中的Cookie时,图片中的Cookie会显示!!
所以我的主要问题是:为什么即使csrf cookie是请求的一部分,DRF也无法读取令牌?