我正在调用具有 CSRF 保护的 REST API。
一切正常。我正在获取 token 并将其发送回服务器。
但是,当我执行第一个请求时,或者当浏览器中未设置 CSRF Cookie 时,它总是会抛出 HTTP 403
错误。
这是因为我没有发送回 CSRF
token ,因为这是服务器发送 Set-Cookie
header 以设置 CSRF 的第一个请求 cookies 。
在我们第一次向受 CSRF 保护的 API 发送请求时,避免此错误的最佳方法是什么?
在发送任何请求之前,我是否应该每次都检查浏览器中是否设置了 CSRF
Cookie?
最佳答案
你可以这样做。这是一个虚拟脚本。
checkIfAuthenticated()
.then( token => {
// user is authorized. use token
})
.catch( err => {
// oops. not authorized probably. authenticate user here.
});
// and your checkifAuthenticated:
function checkifAuthenticated() {
return new Promise((resovle, reject) => {
// perform a http request here to /api?checkauth
if(api_returned_401) {
reject('not authenticated');
} else {
resolve(tokenOrInfo);
}
});
}
关于javascript - 获取 Set-Cookie header 以设置 CSRF Cookie 时避免 HTTP 403 错误的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45522838/