2017-02-27 52 views
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值。

回答

0

找到了答案here。 csrftoken不應該在GET的請求頭中。相反,

fetch('/api/workflows', { credentials: 'include' })... 

它包括cookie,如Fetch docs中所述。

必須爲PUT,PATCH和DELETE請求設置X-CSRFToken

相關問題