简体   繁体   English

Node Express 服务器无法在 AWS ELB 环境中设置 cookie

[英]Node Express server unable to set cookie in AWS ELB environment

I have a middle wear in my Express app that sets a cookie in the clients browser:我的 Express 应用程序中有一个 middle wear,它在客户端浏览器中设置了一个 cookie:

 res.cookie('token', '123');

Everything works perfect on a local environment with the front end calling local the server:一切都在本地环境中完美运行,前端调用本地服务器:

 axios
  .post(`http://localhost:3000/createSomething`, { 'field': "value"})
  .then(res => {
    console.log('res', res)
  })
  .catch(err => {
    return Promise.reject(
      new Error('There is an issue with the /createSomething endpoint')
    );
  });

In this situation the cookie gets set and I can see it in my dev tools under the Cookies section.在这种情况下,cookie 已设置,我可以在我的开发工具中的 Cookies 部分下看到它。 The issue is when I change my front end call to point to the AWS Elastic Beanstalk environment:问题是当我将前端调用更改为指向 AWS Elastic Beanstalk 环境时:

http://localhost:3000/createSomething -> https://testEnvironment.com/createSomething http://localhost:3000/createSomething -> https://testEnvironment.com/createSomething

The call is successful but no cookie is created in the clients browser.调用成功,但客户端浏览器中未创建任何 cookie。 Although, In the response headers I do see:虽然,在响应标头中我确实看到了:

set-cookie: paigetoken=123; Path=/

A few further details:一些进一步的细节:

  • There is a yellow warning symbol at the end of the set-cookie. set-cookie 的末尾有一个黄色警告符号。
  • Using CORS使用 CORS
  • There is an application load balancer in the AWS environment that handles https. Could this be a factor? AWS 环境中有一个应用程序负载均衡器处理 https。这可能是一个因素吗?

How can I resolve this issue and have my Express app in AWS ELB environment successfully set a cookie in the clients browser?如何解决此问题并让我在 AWS ELB 环境中的 Express 应用程序在客户端浏览器中成功设置 cookie? Any insight would be greatly appreciated!任何见解将不胜感激!

You need to pass SameSite=None; Secure您需要传递SameSite=None; Secure SameSite=None; Secure along with the set-cookie information as set-cookie: paigetoken=123; Path=/;SameSite=None; Secure与 set-cookie 信息一起SameSite=None; Secureset-cookie: paigetoken=123; Path=/;SameSite=None; Secure set-cookie: paigetoken=123; Path=/;SameSite=None; Secure

Chrome dosen't allow setting cookies from domain without using SameSite options. Chrome 不允许在不使用SameSite选项的情况下从域设置 cookies。

https://digiday.com/media/what-is-chrome-samesite/ https://digiday.com/media/what-is-chrome-samesite/

PS: This is ignored when request is originated from local environment. PS:当请求来自本地环境时,这将被忽略。 (localhost/127.0.0.1) (本地主机/127.0.0.1)

In NodeJs, It will work something like this.在 NodeJs 中,它会像这样工作。

res.cookie('token', '123', { sameSite: 'None', path: '/', secure: true })

Here's some reference:这里有一些参考:

http://expressjs.com/en/4x/api.html#res.cookie http://expressjs.com/en/4x/api.html#res.cookie

1. Change the request URL: 1.更改请求URL:

Since I'm not totally sure how your environment is set up, the issue may be that the client is requesting information from localhost meaning that it would be requesting data from the clients same machine.由于我不完全确定您的环境是如何设置的,问题可能是客户端正在从localhost请求信息,这意味着它将从客户端的同一台机器请求数据。 Try changing your URL in the client code to:尝试将客户端代码中的 URL 更改为:

`${location.origin}/createSomething`

2. If that doesn't work: 2. 如果这不起作用:

This presents a security issue in most browsers.这在大多数浏览器中都存在安全问题。 Imagine a malicious site overriding a login token cookie for lets say Google.想象一下,一个恶意站点覆盖了 Google 的登录令牌 cookie。 In order for a server to set the cookie, location.origin must match in both the client and the requested endpoint.为了让服务器设置 cookie, location.origin必须在客户端和请求的端点中匹配。

A work around you could use is have the server send a response telling the client to set the cookie on the front-end.您可以使用的解决方法是让服务器发送一个响应,告诉客户端在前端设置 cookie。

For example: on the server you could do something like this to send a header with the cookie information.例如:在服务器上你可以做这样的事情来发送一个带有 cookie 信息的 header。

res.set('X-SetCookie', JSON.stringify({ name: "token", value: "123" }));

Then in the client, something like this to actually set the cookie.然后在客户端中,像这样实际设置 cookie。

axios
  .post(`http://localhost:3000/createSomething`, { 'field': "value"})
  .then(res => {

    // Set cookie function.
    function setCookie({ name, value, expires = 1000*60*60*24*365 }) {
        const time = new Date();
        time.setTime(time.getTime() + expires);
        document.cookie = `${name}=${value};expires=${time.toUTCString()};path=/`;
    }

    // If response has the X-SetCookie header, set the cookie client side.
    if(res.headers.hasOwnProperty("X-SetCookie")) setCookie(JSON.parse(res.headers["X-SetCookie"]));
    
    console.log('res', res)
  })

Just make sure you configure CORS properly so the browser can see the header: Axios get access to response header fields只需确保正确配置 CORS,以便浏览器可以看到 header: Axios 可以访问响应 header 字段

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

相关问题 Websocket 在使用 AWS ELB 的连接节点服务器空闲 60 秒后关闭 - Websocket closing after 60 seconds of being idle while connection node server using AWS ELB express-session 无法在生产环境中设置 connect.sid cookie - express-session unable to set connect.sid cookie in production AWS Lambda 未设置环境变量,节点中未定义 process.env - AWS Lambda Environment Variables not set, process.env undefined in Node AWS http api 网关 + lambda (node/express) 内部服务器错误 - AWS http api gateway + lambda (node/express) Internal Server Error 无法在新的 AWS gRPC ELB 上建立不安全的 gRPC 连接 - Unable to Establish Insecure gRPC connection on the New AWS gRPC ELB 为什么我的 AWS ELB 不工作? 目前无法处理这个请求,HTTP ERROR 503 - Why my AWS ELB does not work? is currently unable to handle this request,HTTP ERROR 503 SSL 到 AWS ELB 和 ELB 到 Tomcat 非 SSL / HTTP - SSL to AWS ELB and ELB to Tomcat non SSL / HTTP 如何自动获取DNS ELB ELB AWS Cloud formation - how to get DNS ELB automatically ELB AWS Cloud formation 节点反应或表达之间发布到 AWS 是否不同? - Is publishing to AWS different between node react or express? 是否有必要在 AWS 中面向 ELB 的互联网后面的 ec2 实例上设置公共 ip? - Is it necessary to set public ip on ec2 instance behind internet facing ELB in AWS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM