[英]Fetch, set-cookies and csrf
我在我的應用程序中使用 Isomorphic fetch 並且我在處理 CSRF 時遇到了一些麻煩。
實際上,我有一個后端在 set-cookies 屬性中向我發送 CSRF-TOKEN:
我在某處讀到這是不可能的,或者直接在我的代碼中訪問這種 cookie 是一種不好的做法。
這樣,我嘗試使用 fetch request 的憑據屬性來做一些事情:
const headers = new Headers({
'Content-Type': 'x-www-form-urlencoded'
});
return this.fetcher(url, {
method: 'POST',
headers,
credentials: 'include',
body: JSON.stringify({
email: 'mail@mail.fr',
password: 'password'
})
});
這樣,我就可以將我的 CSRF cookie 發送回我的服務器以滿足我的需要(這是一個不同的請求,因為它不是同一個請求):
我的問題
我的問題是我的后端需要接收一個 x-csrf-token 標頭,所以我無法將它設置為我的 POST 請求。
我需要什么
如何將set-cookies: CSRF-TOKEN 的值放入下一個請求x-csrf-token標頭中?
在您的場景中,您應該從 CSRF-TOKEN cookie 中讀取數據。 否則它會被標記為 HttpOnly 為 JSESSIONID。 后者意味着您無法從網頁訪問它,而只能自動發送回服務器。
一般來說,從 cookie 中讀取 CSRF 令牌沒有任何問題。 請查看這個很好的討論: 為什么將 CSRF 預防令牌放在 cookie 中很常見?
您可以使用以下代碼讀取您的 cookie(當然不是 HttpOnly)
function getCookie(name) {
if (!document.cookie) {
return null;
}
const xsrfCookies = document.cookie.split(';')
.map(c => c.trim())
.filter(c => c.startsWith(name + '='));
if (xsrfCookies.length === 0) {
return null;
}
return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}
所以 fetch 調用可能看起來像
const csrfToken = getCookie('CSRF-TOKEN');
const headers = new Headers({
'Content-Type': 'x-www-form-urlencoded',
'X-CSRF-TOKEN': csrfToken
});
return this.fetcher(url, {
method: 'POST',
headers,
credentials: 'include',
body: JSON.stringify({
email: 'test@example.com',
password: 'password'
})
});
是的標頭名稱取決於您的服務器。 例如使用 fetch 設置 CSRF 令牌的 django 用例是這樣的:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
'X-CSRFToken': get_token
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.