node.js - HttpOnly cookie 可以在 Node 客户端中访问吗?

标签 node.js cookies cookie-httponly

我是 Node 新手,正在学习一些教程。我有一个运行此代码的简单 Node 服务器:

// SERVER CODE
const http = require('http');
const Cookies = require('cookies');
const port = 3000;

const requestHandler = (request, response) => {
  cookies = new Cookies(request, response);
  cookies.set("foo", "bar", { httpOnly: true });

  response.end('Hello Node.js Server!');
}

const server = http.createServer(requestHandler);

server.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err);
  }

  console.log(`server is listening on ${port}`);
})

我还有另一个 .js 文件尝试访问此服务器:

//CLIENT CODE
const http = require('http')

http.get('http://machine_name:3000', (
    console.log(res.headers['set-cookie']);
});

根据我的理解,客户端 Javascript 应该无法使用 httponly cookie。当我运行客户端代码时,我得到:

[ 'foo=bar; path=/; httponly' ]

这是对的吗?是我设置不正确吗?我觉得这是一个错误,因为 httponly 属性意味着我不应该能够通过 Javascript 访问它。

最佳答案

您正在做的是以正确的方式进行,您可以使用浏览器尝试。

有关内容的存档索引:

// index.js file
const http = require('http');
const Cookies = require('cookies');
const port = 3000;

const requestHandler = (request, response) => {
  cookies = new Cookies(request, response);
  cookies.set("foo", "bar", { httpOnly: true });

  response.end('Hello Node.js Server!');
}

const server = http.createServer(requestHandler);

server.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err);
  }

  console.log(`server is listening on ${port}`);
})

当你执行命令时

node index.js

然后您打开浏览器,打开控制台并执行以下命令

console.log( document.cookie ) // this not return your cookies

但是如果您有{ httpOnly: false },您可以获得以下内容:

“其他cookies;foo=bar

This is because JavaScript uses cookies more in the browser itself than in the console, if you have the httpOnly flag activated you can be 100% sure that no JS script can use it.

Read more about cookies

关于node.js - HttpOnly cookie 可以在 Node 客户端中访问吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878943/

相关文章:

javascript - cookie 是否被视为 DOM 树的一部分?

php - 防止用户文本区域输入

python - 如何在Flask中设置HTTPONLY cookie

node.js - 在 hummus js 中,我如何绘制一个透明的填充矩形?

node.js - 检查 Node.js rest API 上的资源所有权

javascript - Application Insights 安全 cookie

oauth-2.0 - 如何验证在 FastAPI 中作为 HttpOnly cookie 发送的 JWT?

node.js - Mocha beforeEach vs 执行前

javascript - Firebase 函数从外部 API 调用返回错误文本

laravel - Laravel 5.6-自耗API的Passport JWT httponly cookie SPA身份验证?