简体   繁体   中英

"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. 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:

// 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. 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"

Bear in mind that I am testing the API locally on port 3000 while the endpoint is deployed on a testing server using 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. Also make sure this will be disabled only in the dev setup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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