简体   繁体   English

“通过 Set-Cookie 设置 cookie 的尝试被阻止”与反应

[英]"The attempt to set cookie via Set-Cookie was blocked" with react

I am working on a small project where users authenticate using their email and password before accessing their profile.我正在做一个小项目,用户在访问他们的个人资料之前使用他们的 email 和密码进行身份验证。 The backend uses cookies which are set when correct email and password are submitted to the auth API. I have created an instance of axios to handle the api calls and here is how it looks:后端使用 cookies,这是在正确的 email 和密码提交给 auth API 时设置的。我创建了一个 axios 的实例来处理 api 调用,下面是它的外观:

// Step-1: Create a new Axios instance with a custom config.
// The timeout is set to 10s. If the request takes longer than
// that then the request will be aborted.
const customAxios = axios.create({
  ...apiConfig,
  timeout: 10000,
  withCredentials: true,
// custom headers can be added here as shown below
// headers: { 'api-key': 'eyJz-CI6Ikp-4pWY-lhdCI6' }
});

// Step-2: Create request, response & error handlers
const requestHandler = (request) => {
request.headers["Accept"] = "application/json";
request.headers["Content-Type"] = "application/json";
return request;
};

const errorHandler = (error) => {
  return Promise.reject(error);
};

customAxios.interceptors.request.use(
  (request) => requestHandler(request),
  (error) => errorHandler(error)
);

customAxios.interceptors.response.use(
 (response) => responseHandler(response),
 (error) => errorHandler(error) 
);

The point is, whenever I try to call the auth API with correct credentials, it returns success but the Set-Cookie header in the response has a warning and the cookies are not set in the browser.关键是,每当我尝试使用正确的凭据调用 auth API 时,它都会返回成功,但响应中的 Set-Cookie header 会发出警告,并且 cookies 未在浏览器中设置。 Here is the warning:这是警告:

"The attempt to set cookie using a Set-Cookie was block because it had the "SameSite=Strict" attribute but came from a cross-site response which was not the response to the top-level navigation" “使用 Set-Cookie 设置 cookie 的尝试被阻止,因为它具有“SameSite=Strict”属性,但来自跨站点响应,这不是对顶级导航的响应”

Bear in mind that I am testing the API locally on port 3000 while the endpoint is deployed on a testing server using Chrome.请记住,我正在端口 3000 上本地测试 API,而端点部署在使用 Chrome 的测试服务器上。

Thanks谢谢

Sounds like your dev setup with two different origins is the problem (and hey, your security policies are working!) Disable the SameSite=Strict in development mode, or extend it to also accept cookies from localhost:3000 (the API domain), not just the same domain where the frontend is served.听起来你的开发设置有两个不同的来源是问题所在(嘿,你的安全策略正在工作!)在开发模式下禁用SameSite=Strict ,或将其扩展为也接受来自localhost:3000 (API 域)的 cookies,而不是与前端服务的域相同。 Also make sure this will be disabled only in the dev setup还要确保这只会在开发设置中被禁用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM