0
我試圖訪問受DRF session authentication保護的API端點。這需要經過CSRF的cookie的請求頭,我曾問過繼Django docs,就像這樣:如何使用會話驗證向Django Rest Framework發出HTTP請求?
import * as Cookies from "js-cookie";
var csrftoken = Cookies.get('csrftoken');
fetch('/api/myendpoint', { headers: { 'X-CSRFToken': csrftoken }})
.then(response => ...)
我已經打開的會話認證在我的settings.py這樣的:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
Django登錄和身份驗證對正常頁面正常工作,但不適用於我的API調用。我總是收到一個403錯誤的響應Authentication credentials were not provided
。我已通過查看Chrome網絡面板中的請求,檢查了X-CSRFToken標頭值是否已正確設置爲當前的csrftoken cookie值。