如何设置http only cookie

如何解决如何设置http only cookie

我目前正在为应用实现登录/注册/注销功能,并使用 JWT。我的 MERN 应用程序在两个不同的端口上运行:前端 - 3000,后端 - 10000。我成功地从前到后发送和获取数据,但是在设置 httponly cookie 以在那里存储 JWT 令牌时,我看到了令牌,它的生成没有错误,我得到了成功的响应:

Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 44
Content-Type: text/html; charset=utf-8
Date: Tue,08 Jun 2021 18:40:02 GMT
ETag: W/"2c-4r7DVPOVNJvegkHqxvDpBQ6Yp8Y"
Keep-Alive: timeout=5
Set-Cookie: nToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwYmY1ZjNlNzU0NmFhMTMxY2M5M2U1MyIsImVtYWlsIjoic29tZWVtYWlsQGdtYWlsLmNvbSIsImlhdCI6MTYyMzE3NzYwMSwiZXhwIjoxNjU0NzM0NTI3fQ.9uNwg6PIfGDJnmbt8qNd4IDt_9JDHuno_IUL9FSwz-U; Max-Age=900; Path=/; Expires=Tue,08 Jun 2021 18:55:02 GMT; HttpOnly
X-Powered-By: Express

一些日志以确保一切正常:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwYmY1ZjNlNzU0NmFhMTMxY2M5M2U1MyIsImVtYWlsIjoic29tZWVtYWlsQGdtYWlsLmNvbSIsImlhdCI6MTYyMzE3NzYwMSwiZXhwIjoxNjU0NzM0NTI3fQ.9uNwg6PIfGDJnmbt8qNd4IDt_9JDHuno_IUL9FSwz-U
POST /api/user 200 4311.690 ms - 44

最后,访问 /api/user 时调用的 controller.js 文件部分:

getone: async (req,res) => {

    try {
      const user = await User.findOne({ email: req.body.user.email });
      if (!user) {
        return "User doesn't exist";
      }
      // Check password
      const isMatch = await bcrypt.compare(
        req.body.user.password,user.password
      );
      console.log(req.body.user.password,user.password,isMatch);
      if (isMatch) {
        // User matched
        // Create JWT Payload
        const payload = {
          id: user._id,email: user.email,};
        // Sign token
        try {
          const token = await jwt.sign(payload,process.env.SECRET,{
            expiresIn: 31556926,// 1 year in seconds
          });
          console.log(token)
           res.cookie('nToken',token,{ maxAge: 900000,httpOnly: true });
          return `Succesfully logged in as ${user.email}`
        } catch (err) {
          return err.message;
        }
      } else {
        return "Wrong password";
      }
    } catch (err) {
      return "Error: " + err.message;
    }
  },

它实现了登录功能

所以我问这个问题为什么我在 devtools->cookies 中没有看到 httponly cookie 我的 useEffect 调用后端:

useEffect(async () => {
    const articles = await axios({method: "POST",url: vars.BACKENDURL + "/user",data: { user: {
    email: "someemail@gmail.com",password: "mypass123"
}
}});

前端得到的响应:

config:
adapter: ƒ xhrAdapter(config)
data: "{\"user\":{\"email\":\"someemail@gmail.com\",\"password\":\"mypass123\"}}"
headers:
Accept: "application/json,text/plain,*/*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxBodyLength: -1
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "http://localhost:10000/api/user"
validateStatus: ƒ validateStatus(status)
xsrfCookieName: "XSRF-TOKEN"
xsrfheaderName: "X-XSRF-TOKEN"
__proto__: Object
data: "Succesfully logged in as someemail@gmail.com"
headers: {content-length: "44",content-type: "text/html; charset=utf-8"}
request: XMLHttpRequest {readyState: 4,timeout: 0,withCredentials: false,upload: XMLHttpRequestUpload,onreadystatechange: ƒ,…}
status: 200
statusText: "OK"

  • 由于某种原因,网络中显示了两个对用户 api 的请求,这是第二个:

Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Tue,08 Jun 2021 18:39:57 GMT
Keep-Alive: timeout=5
vary: Access-Control-Request-Headers
X-Powered-By: Express

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?