1

我正在调用具有 CSRF 保护的 REST API。

一切正常。我正在获取令牌并将其发送回服务器。

但是,当我执行第一个请求或浏览器中未设置 CSRF Coo​​kie 时,它​​总是会引发HTTP 403错误。

这是因为我没有发CSRF回令牌,因为这是服务器发送Set-Cookie标头以设置 CSRF Coo​​kie 的第一个请求。

第一次向受 CSRF 保护的 API 发送请求时,避免此错误的最佳方法是什么?

在发送任何请求之前,我是否应该每次检查CSRF浏览器中是否设置了 Cookie?

4

1 回答 1

1

你可以做这样的事情。这是一个虚拟脚本。

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);
    }
  });
}

于 2017-08-05T14:35:17.947 回答