我正在尝试使用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)
我的Rest框架设置:
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 I actually get a token in my cookie 时 .
当我添加@csrf_exempt注释时,会打印 {'csrftoken': 'HZc8vPqoad...7eIvTzep', 'sessionid': 'n71c....g5c7'}
.
在我的角度代码中,我还尝试将csrf标记附加为带有'X-CSRFToken'的请求标头,但我注意到两件事
1)在我的请求中,我从_2702294获得的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时, The cookie in the image shows up!!
所以我的主要问题是:为什么即使csrf cookie是请求的一部分,DRF也无法读取令牌?